如何将以毫秒为单位的包含7位数字的日期字符串转换为Python中的日期 [英] How do I convert a date string containing 7 digits in milliseconds into a date in Python

查看:170
本文介绍了如何将以毫秒为单位的包含7位数字的日期字符串转换为Python中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当千位位数为6位时,%f起作用,但如果位数超过6位,则抛出错误。我有一个临时解决方案,将第7位数字硬编码为0,但是还有更好的方法吗?目前以下作品

When the milliseonds have 6 digits, %f works, but it throws an error if there are more than 6 digits. I have a temporary solution by hardcoding a 0 for the 7th digit, but is there a better way to do? Currently the below works

print (datetime.datetime.strptime(('2014-11-19 00:00:00.0000000').strip(), '%Y-%m-%d  %H:%M:%S.0%f')).date()


推荐答案

根据 datetime.strptime() https://docs.python.org/2/library/datetime.html #strftime-and-strptime-behavior ,技术说明(4),%f仅接受1-6个字符:

According to the documentation of datetime.strptime() https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior, technical note (4), %f accepts only 1 - 6 chars:


%f是C标准
中格式字符集的扩展(但在datetime对象中单独实现,因此始终有
可用)。与strptime()方法一起使用时,%f指令
接受右侧的1到6位数字和零填充。

%f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.

我认为您没有正确解决问题。您不应该在字符串前添加零,而应将所有内容都丢弃到6以上(这对时间贡献意义不大)。

I do NOT believe you have solved the problem correctly. You should not prefix the string with zero, but instead drop everything past 6 (which is less significant to contributing to time).

类似这样的事情:

s='2014-11-19 00:00:00.0000000'
print (datetime.datetime.strptime((s[:26]).strip(), '%Y-%m-%d  %H:%M:%S.%f')).date()

这篇关于如何将以毫秒为单位的包含7位数字的日期字符串转换为Python中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆