Normalize different date data into single format in Python [duplicate]

主宰稳场 提交于 2021-02-07 13:10:32

问题


I am currently analyzing a dateset which contains so many different date types like

12/31/1991
December 10, 1980
September 25, 1970
2005-11-14
December 1990
October 12, 2005
1993-06-26

Is there a way to normalize all the date data into single format 'YYYY-MM-DD' ? I am familiar with datetime package in Python, but what's the best way to approach this problem so that it can handle all the different date types.


回答1:


If you are okay with using a library, you can use the dateutil library (I believe it comes already installed for Python 3 +) , specifically the dateutil.parser.parse function, and parse all the dates into datetime objects, and then use datetime.datetime.strftime() to parse them back into strings in the format - 'YYYY-MM-DD' . Example -

>>> s = """12/31/1991
... December 10, 1980
... September 25, 1970
... 2005-11-14
... December 1990
... October 12, 2005
... 1993-06-26"""

>>> from dateutil import parser
>>> for i in s.splitlines():
...     d = parser.parse(i)
...     print(d.strftime("%Y-%m-%d"))
...
1991-12-31
1980-12-10
1970-09-25
2005-11-14
1990-12-10
2005-10-12
1993-06-26

A thing to note, dateutil.parser.parse would use the current datetime to make up for any parts of the datetime if they are missing in the string (as can be seen above in the parsing of 'December 1990' , which got parsed as - 1990-12-10 as 10 is the current date) .




回答2:


I have solved this issue:

from  dateutil.parser import parse
dt = parse(str(row))
print(dt.strftime('%Y-%m-%d'))

It is able to handle different date types.



来源:https://stackoverflow.com/questions/33051147/normalize-different-date-data-into-single-format-in-python

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