我想转换不同类型的格式(str像Sep 2019,int像2018,float到datetime.datetime)

时间:2019-07-10 13:30:28

标签: python pandas datetime

SELECT 
   User.*, 
   Store.*, 
   Sqr((User.Lat - Store.Lat)^2+(User.Long - Store.Long)^2) AS distance
FROM User, Store

我需要将它们转换为一种格式,我尝试了此代码,但其中包含许多错误,感谢您的帮助

2010-01-01 00:00:00
Dec 2017
2008-06-01 00:00:00
2018-06-01 00:00:00
2009
2018-11-01 00:00:00
Feb 2018
2005
Aug 2017

1 个答案:

答案 0 :(得分:1)

dateutil模块提供了一个parser module,它可以检测各种格式并将其转换为datetime对象。

from dateutil.parser import parse
dates = [
    '2010-01-01 00:00:00',
    'Dec 2017',
    '2008-06-01 00:00:00',
    '2018-06-01 00:00:00',
    '2009',
    '2018-11-01 00:00:00',
    'Feb 2018',
    '2005',
    'Aug 2017'
]

[parse(date) for date in dates]

结果:

[datetime.datetime(2010, 1, 1, 0, 0),
 datetime.datetime(2017, 12, 10, 0, 0),
 datetime.datetime(2008, 6, 1, 0, 0),
 datetime.datetime(2018, 6, 1, 0, 0),
 datetime.datetime(2009, 7, 10, 0, 0),
 datetime.datetime(2018, 11, 1, 0, 0),
 datetime.datetime(2018, 2, 10, 0, 0),
 datetime.datetime(2005, 7, 10, 0, 0),
 datetime.datetime(2017, 8, 10, 0, 0)]