将时间字符串转换为日期时间格式可能非常繁琐,因为我们需要确保每个新数据遵循转换函数所需的确切格式,否则会引发错误。
一种好方法是使用 dateutil.parser 包,它更加灵活。 它还可以支持一些模糊性。有了这个包,即使有些数据的格式与我们预期的略有不同,也不会导致错误。
通常的时间戳转换方法
import datetime
# without milliseconds format
item = '2022/01/01 10:49:12'
result = datetime.datetime.strptime(item, "%Y/%m/%d %H:%M:%S")
print(result.year)
# with milliseconds format
item = '2022/01/01 10:49:12.213'
result = datetime.datetime.strptime(item, "%Y/%m/%d %H:%M:%S.%f")
print(result.year)
# 下面的方法会报错,因为新数据的格式没有毫秒格式
# in the above example if there is a new item that doesn't follow the milliseconds format, it will raise error
item = '2022/01/01 10:49:12'
result = datetime.datetime.strptime(item, "%Y/%m/%d %H:%M:%S.%f")
print(result.year)
2022
2022
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-a29c39b3ca30> in <module>
15 # in the above example if there is a new item that doesn't follow the milliseconds format, it will raise error
16 item = '2022/01/01 10:49:12'
---> 17 result = datetime.datetime.strptime(item, "%Y/%m/%d %H:%M:%S.%f")
18
19 print(result.year)
D:\Anaconda3\lib\_strptime.py in _strptime_datetime(cls, data_string, format)
575 """Return a class cls instance based on the input string and the
576 format string."""
--> 577 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
578 tzname, gmtoff = tt[-2:]
579 args = tt[:6] + (fraction,)
D:\Anaconda3\lib\_strptime.py in _strptime(data_string, format)
357 if not found:
358 raise ValueError("time data %r does not match format %r" %
--> 359 (data_string, format))
360 if len(data_string) != found.end():
361 raise ValueError("unconverted data remains: %s" %
ValueError: time data '2022/01/01 10:49:12' does not match format '%Y/%m/%d %H:%M:%S.%f'
利用 parser in dateutil 更加稳定的方法
from dateutil.parser import *
# for the same example above, it will not raiser error
item = '2022/01/01 10:49:12'
result = parse(item)
print(result.year)
item = '2022/01/01 10:49:12.213'
result = parse(item)
print(result.year)
2022
2022
更多价值文章,请访问:
data science tribe
基于大数据统计的英语词汇和查询:
english learning by example