简体   繁体   English

在Python中将微秒时间戳转换为datetime

[英]Convert microsecond timestamp to datetime in Python

I'm pulling a cookie expiration date from Google Chrome. 我正在从Google Chrome中提取Cookie到期日期。 From what it looks like, Chrome is storing cookie expirations with a timestamp that uses 1601-01-01 00:00:00 UTC as the epoch. 从它的外观来看,Chrome正在使用时间戳存储Cookie过期,该时间戳使用1601-01-01 00:00:00 UTC作为纪元。 My current implementation is as follows: 我目前的实施如下:

stamp = int(result[3])
date = datetime.datetime.fromtimestamp(stamp / 10000000.0)
print date.year

However, this is producing the wrong date (off by about a year). 然而,这产生了错误的日期(约一年)。 What am I doing wrong here? 我在这做错了什么?

Another option, getting tzinfo from the standard library since Python 3.2 (for older Python versions you can get if from pytz ): 另一种选择,从Python 3.2开始从标准库中获取tzinfo (对于较旧的Python版本,如果来自pytzpytz ):

>>> import pytz
>>> from datetime import datetime, timedelta, timezone
>>> epoch = datetime(1601, 1, 1, tzinfo=timezone.utc)
>>> cookie_microseconds_since_epoch = 13022344559000000
>>> cookie_datetime = epoch + timedelta(microseconds=cookie_microseconds_since_epoch)
>>> str(cookie_datetime)
'2013-08-29 13:55:59+00:00'

I assume that the difference to your expected value is the timezones offset. 我假设与期望值的差异是时区偏移量。

Update: 更新:

As @JFSebastian correctly points out, if you are using implicit UTC naive datetime objects, tzinfo is redundant and the above can be simplified to: 正如@JFSebastian正确指出的那样,如果你使用隐式UTC 天真 datetime对象, tzinfo是多余的,上面的内容可以简化为:

>>> from datetime import datetime, timedelta
>>> epoch = datetime(1601, 1, 1)
>>> cookie_microseconds_since_epoch = 13022344559000000
>>> cookie_datetime = epoch + timedelta(microseconds=cookie_microseconds_since_epoch)
>>> str(cookie_datetime)
'2013-08-30 13:55:59'

I'm not sure what data you're starting with but here is an example starting from an integer timestamp. 我不确定你开始的数据是什么,但这里是一个从整数时间戳开始的例子。 Assumes the pytz module is present (which I recommend highly). 假设pytz模块存在(我高度推荐)。

>>> import datetime, pytz
>>> x = datetime.datetime.fromtimestamp(0)
>>> x = x.replace(tzinfo=pytz.UTC)
>>> str(x)
'1970-01-01 00:00:00+00:00'
>>> d = datetime.timedelta(365 * (1970 - 1601))
>>> str(x - d)
'1601-03-31 00:00:00+00:00'
>>> d = datetime.timedelta(365 * (1970 - 1601) + 31 + 28 + 31 - 1)
>>> str(x - d)
'1601-01-01 00:00:00+00:00'
>>> str(d)
'134774 days, 0:00:00'

So there you have it. 所以你有它。 Conversion between a Jan 1 1601 epoch and a Jan 1 1970 epoch is 134774 days. 1601年1月1日和1970年1月1日之间的转换是134774天。

Why that number of days? 为什么这么多天? Leap years! 闰年! We added a certain number of days, not years. 我们增加了一定天数,而不是几年。 (In fact, adding years is not directly supported in timedelta objects.) (实际上, timedelta对象不直接支持添加年份 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM