Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of unix epoch time to windows epoch time in python

Quick question: Is there a pythonic (whether in the standard libraries or not) way to convert unix 32-bit epoch time to windows 64-bit epoch time and back again?

like image 297
user1040625 Avatar asked Dec 29 '11 16:12

user1040625


2 Answers

You can convert a POSIX timestamp to a datetime with

>>> tstamp = 1325178061  # right about now
>>> from datetime import datetime
>>> datetime.fromtimestamp(tstamp)
datetime.datetime(2011, 12, 29, 18, 1, 1)

The fromtimestamp named constructor accepts POSIX timestamps on all platforms (!).

Conversion to a Windows timestamp would be a matter of subtracting the Windows epoch, which Wikipedia says is January 1, 1601, and converting the resulting timedelta to a number of seconds:

>>> W_EPOCH = datetime(1601, 1, 1)
>>> (datetime.fromtimestamp(tstamp) - W_EPOCH).total_seconds()
12969655261.0

Now you've got a float that you convert to int and store as a 64-bit quantity in whichever way you like.

like image 97
Fred Foo Avatar answered Sep 30 '22 09:09

Fred Foo


To convert from a Windows EPOCH timestamp to a datetime object (but not the other way around); here's a solution I came up with:

from datetime import datetime, timezone
def convert_from(windows_timestamp: int) -> datetime:
    unix_epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
    windows_epoch = datetime(1601, 1, 1, tzinfo=timezone.utc)
    epoch_delta = unix_epoch - windows_epoch
    windows_timestamp_in_seconds = windows_timestamp / 10_000_000
    unix_timestamp = windows_timestamp_in_seconds - epoch_delta.total_seconds()

    return datetime.utcfromtimestamp(unix_timestamp)

This allows you to pass in the Windows timestamp as is and it will spit out a valid Python datetime object.

NOTE: This is Python 3 specific.

like image 43
Jitsusama Avatar answered Sep 30 '22 10:09

Jitsusama