更加稳定的时间字符串转换为时间戳(datetime object)方法

将时间字符串转换为日期时间格式可能非常繁琐,因为我们需要确保每个新数据遵循转换函数所需的确切格式,否则会引发错误。

一种好方法是使用 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值