Python: convert date from string to number
我有一个简单的问题。我需要将字符串格式的日期转换为数字:
1 2 3 | time = '2014-03-05 07:22:26.976637+00:00' type(time) str |
我想把这个日期转换成一个唯一的数字
谢谢您。
在python 3.7+中:
1 2 3 | >>> from datetime import datetime >>> datetime.fromisoformat('2014-03-05 07:22:26.976637+00:00').timestamp() 1394004146.976637 |
有两个步骤:
将输入的RFC-3339时间字符串转换为日期时间对象1 2 3 4 5 6 | #!/usr/bin/env python from datetime import datetime time_str = '2014-03-05 07:22:26.976637+00:00' utc_time = datetime.strptime(time_str[:26], '%Y-%m-%d %H:%M:%S.%f') assert time_str[-6:] == '+00:00' |
。查找给定日期时间的从epoch开始的微秒数
1 2 3 4 5 6 7 8 9 10 11 | from datetime import datetime, timedelta epoch = datetime(1970, 1, 1) def timestamp_microsecond(utc_time): td = utc_time - epoch assert td.resolution == timedelta(microseconds=1) return (td.days * 86400 + td.seconds) * 10**6 + td.microseconds print(timestamp_microsecond(utc_time)) # -> 1394004146976637 |
优点是您可以将这个唯一的数字转换回相应的UTC时间:
1 2 | utc_time = epoch + timedelta(microseconds=1394004146976637) # -> datetime.datetime(2014, 3, 5, 7, 22, 26, 976637) |
。
如果需要支持任意的UTC偏移量(而不仅仅是UTC时间),请使用链接。
如果您需要接受一个闰秒作为输入时间,请参见python-datetime没有正确地计算闰秒?
I would like to convert this date to a unique number
号
标准的Unix操作是转换为从epoch开始的秒数。但是,如果您只想要一个唯一的号码:
1 2 3 | >>> time = '2014-03-05 07:22:26.976637+00:00' >>> int(''.join(c for c in time if c.isdigit())) 201403050722269766370000L |
如果希望使用python datetime对象而不是唯一的数字,请使用:
1 2 3 4 | >>> from dateutil import parser >>> dt = parser.parse(time) >>> dt datetime.datetime(2014, 3, 5, 7, 22, 26, 976637, tzinfo=tzutc()) |
号