Python:将日期从字符串转换为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32727538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: convert date from string to number
提问by emax
how I have a simple question. I need to convert a date in string format to a number:
我怎么有一个简单的问题。我需要将字符串格式的日期转换为数字:
time = '2014-03-05 07:22:26.976637+00:00'
type(time)
str
I would like to convert this date to a unique number
我想将此日期转换为唯一数字
Thank you.
谢谢你。
采纳答案by jfs
In Python 3.7+:
在 Python 3.7+ 中:
>>> from datetime import datetime
>>> datetime.fromisoformat('2014-03-05 07:22:26.976637+00:00').timestamp()
1394004146.976637
There are two steps:
有两个步骤:
Convert input rfc-3339 time string into datetime object
将输入的 rfc-3339 时间字符串转换为日期时间对象
#!/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'
Find number of the microseconds since Epoch for given datetime
查找给定日期时间自纪元以来的微秒数
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
The advantage is that you could convert this unique number back to the corresponding UTC time:
优点是您可以将此唯一数字转换回相应的 UTC 时间:
utc_time = epoch + timedelta(microseconds=1394004146976637)
# -> datetime.datetime(2014, 3, 5, 7, 22, 26, 976637)
Follow the links if you need to support arbitrary utc offsets (not just UTC time).
如果您需要支持任意 utc 偏移量(不仅仅是 UTC 时间),请点击链接。
If you need to accept a leap second as the input time; see Python - Datetime not accounting for leap second properly?
如果需要接受闰秒作为输入时间;请参阅Python - Datetime 没有正确考虑闰秒?
回答by John1024
I would like to convert this date to a unique number
我想将此日期转换为唯一数字
The standard unix thing to do would be to convert to seconds since epoch. However, if you just want a unique number:
标准的 unix 要做的事情是转换为自纪元以来的秒数。但是,如果您只想要一个唯一的数字:
>>> time = '2014-03-05 07:22:26.976637+00:00'
>>> int(''.join(c for c in time if c.isdigit()))
201403050722269766370000L
If, instead of a unique number, you want a python datetime object, then use:
如果你想要一个 python datetime 对象而不是唯一的数字,那么使用:
>>> from dateutil import parser
>>> dt = parser.parse(time)
>>> dt
datetime.datetime(2014, 3, 5, 7, 22, 26, 976637, tzinfo=tzutc())