如何格式化日期到1900年代? [英] How to format date to 1900's?
问题描述
我正在预处理数据,其中一栏代表日期,例如'6/1/51'
I'm preprocessing data and one column represents dates such as '6/1/51'
我正在尝试将字符串转换为日期对象,到目前为止,我所拥有的是:
I'm trying to convert the string to a date object and so far what I have is:
date = row[2].strip()
format = "%m/%d/%y"
datetime_object = datetime.strptime(date, format)
date_object = datetime_object.date()
print(date_object)
print(type(date_object))
我面临的问题是将2051改为1951.
The problem I'm facing is changing 2051 to 1951.
我尝试写
format = "%m/%d/19%y"
但是它给了我一个ValueError.
But it gives me a ValueError.
ValueError: time data '6/1/51' does not match format '%m/%d/19%y'
我无法轻松地在线找到答案,所以我在这里问.谁能帮我这个忙吗?
I couldn't easily find the answer online so I'm asking here. Can anyone please help me with this?
谢谢.
推荐答案
使用'%m/%d/%y'
解析没有世纪的日期,然后:
Parse the date without the century using '%m/%d/%y'
, then:
year_1900 = datetime_object.year - 100
datetime_object = datetime_object.replace(year=year_1900)
您应该对此附加条件,以便仅在1900年代的日期进行设置,例如今天之后的任何日期.
You should put conditionals around that so you only do it on dates that are actually in the 1900's, for example anything later than today.
这篇关于如何格式化日期到1900年代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!