Saq*_*Ali -2 python datetime epoch
我有以下字符串表示 UTC 时间戳: 2017-12-03T20:38:00.971261Z
我想将其转换为 Posix 时间戳(即:自纪元以来的秒数)使用此在线转换器(https://www.epochconverter.com/)我知道答案是1512333480
但是,当我执行以下代码时,结果将关闭 1800 秒 - 30 分钟:
>>> temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> ctime = int(datetime.datetime(temp_time1.year,
temp_time1.month,
temp_time1.day,
temp_time1.hour,
temp_time1.minute,
temp_time1.second,
temp_time1.microsecond,
pytz.timezone('Europe/London')).strftime('%s'))
>>> print ctime
1512351480
Run Code Online (Sandbox Code Playgroud)
有人知道我在这里想念什么吗?
您创建了一个新的时间戳并将其放入欧洲/伦敦时区。这与UTC不同。PyTZ 数据库中的欧洲/伦敦时区包括历史偏移,这些会影响datetime.datetime()解释时区的方式。
只需在您已经从字符串中解析的对象上使用该datetime.timestamp()方法datetime:
>>> import datetime
>>> temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> temp_time1.timestamp()
1512333480.971261
Run Code Online (Sandbox Code Playgroud)
您的原始temp_time1日期时间对象与时区无关,因此该timestamp()对象已经假定不必进行时区转换。
如果您Europe/London出于某种原因必须首先应用时区,那么至少使用该timezone.localize()方法来应用正确的偏移量:
>>> import pytz
>>> pytz.timezone('Europe/London').localize(temp_time1)
datetime.datetime(2017, 12, 3, 20, 38, 0, 971261, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)
>>> pytz.timezone('Europe/London').localize(temp_time1).timestamp()
1512333480.971261
Run Code Online (Sandbox Code Playgroud)
对于 Python 2 和 Python 3.0、3.1 或 3.2,如果datetime.timestamp()不可用,请减去纪元日期:
>>> (temp_time1 - datetime.datetime(1970, 1, 1)).total_seconds()
1512333480.971261
Run Code Online (Sandbox Code Playgroud)
在UTC处理时区感知datetime实例时添加时区:
>>> (pytz.timezone('Europe/London').localize(temp_time1) - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
1512333480.971261
Run Code Online (Sandbox Code Playgroud)
组合成一个函数:
def datetime_to_timestamp(dt, epoch=datetime.datetime(1970, 1, 1)):
if dt.tzinfo is not None:
epoch = pytz.utc.localize(epoch)
return (dt - epoch).total_seconds()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |