Convert microsecond timestamp to datetime in Python

I am pulling a cookie expiration date from Google Chrome. Be that as it may, Chrome stores cookie outputs with a timestamp, which uses 1601-01-01 00:00:00 UTC as an era. My current implementation is as follows:

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

However, this leads to an incorrect date (after about a year). What am I doing wrong here?

+5
source share
2 answers

Another option getting tzinfofrom the standard library with Python 3.2 (for older versions of Python you can get if from pytz):

>>> 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 in the expected value is a temporary offset.

Update:

@J.F.Sebastian, 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'
+7

, , , . 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'

, . 1 1601 1 1970 134774 .

? ! , . ( timedelta.)

+1

All Articles