python将日期转换为时间戳_python – 将日期时间转换为时间戳,然后再返回
这是一个众所周知的
Python 3.4 issue:
from datetime import datetime
local = datetime(2014, 1, 30, 23, 59, 40, 1999)
datetime.fromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1998)
注意:微秒消失了. .timestamp()已经返回略小于1999微秒的结果:
from decimal import Decimal
local.timestamp()
1391126380.001999
Decimal(local.timestamp())
Decimal('1391126380.0019989013671875')
from datetime import datetime
local = datetime(2014, 1, 30, 23, 59, 40, 1999)
datetime.fromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1999)
要解决此问题,您可以使用显式公式:
from datetime import datetime, timedelta
local = datetime(2014, 1, 30, 23, 59, 40, 1999)
datetime.utcfromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1998) # UTC time
datetime(1970, 1, 1) + timedelta(seconds=local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1999) # UTC time
注意:所有示例中的输入都是本地时间,但结果是最后一次的UTC时间.
