Skip to main content
 首页 » 编程设计

Python:将日期从字符串转换为数字

2025年05月04日44开发

我怎么有一个简单的问题。我需要将字符串格式的日期转换为数字:

time = '2014-03-05 07:22:26.976637+00:00' 
type(time) 
      str 

我想把这个日期转换成一个唯一的数字

谢谢。

请您参考如下方法:

在 Python 3.7+ 中:

>>> from datetime import datetime 
>>> datetime.fromisoformat('2014-03-05 07:22:26.976637+00:00').timestamp() 
1394004146.976637 

有两个步骤:

Convert input rfc-3339 time string into datetime object

#!/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 

优点是您可以将这个唯一数字转换回相应的 UTC 时间:

utc_time = epoch + timedelta(microseconds=1394004146976637) 
# -> datetime.datetime(2014, 3, 5, 7, 22, 26, 976637) 

如果您需要支持任意 utc 偏移量(不仅仅是 UTC 时间),请点击链接。

如果需要接受闰秒作为输入时间;见Python - Datetime not accounting for leap second properly?