How to format date to 1900's?

落爺英雄遲暮 提交于 2019-12-11 01:43:34

问题


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))

The problem I'm facing is changing 2051 to 1951.

I tried writing

    format = "%m/%d/19%y"

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?

Thanks.


回答1:


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)

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.



来源:https://stackoverflow.com/questions/49950741/how-to-format-date-to-1900s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!