Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to convert unixtimestamp and timezone into datetime object?

I have a csv file with the datetime in unixtimestamp format with milliseconds and timezone information in milliseconds as well. I want to convert this into a more usable datetime format for further processing.

For example, the time is 1437323953822 and timezone is -14400000.

I can convert the timestamp into a datetime by using

datetime.datetime.fromtimestamp(1437323953822/1000)

But how do I now incorporate the timezone which is -4 UTC time from what I know.

(-14400000 / 1000 / 60 / 60) = -4

How do I use this timezone to get the actual time?

like image 855
sfactor Avatar asked Sep 01 '15 06:09

sfactor


2 Answers

fromtimestamp can also take another parameter for the timezone, a subclass of tzinfo:

classmethod datetime.fromtimestamp(timestamp[, tz])

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Else tz must be an instance of a class tzinfo subclass, and the timestamp is converted to tz‘s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).

like image 135
Peter Wood Avatar answered Sep 29 '22 14:09

Peter Wood


fromtimestamp() already returns your local time i.e., you don't need to attach the utc offset if fromtimestamp() determines it correctly automatically:

#!/usr/bin/env python
from datetime import datetime

local_time = datetime.fromtimestamp(1437323953822 * 1e-3)
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)

fromtimestamp() may fail in some cases e.g., if the local timezone had a different utc offset in the past and fromtimestamp() does not use a historical timezone database on a given platform (notably, Windows). In that case, construct the local time explicitly from utc time and the given utc offset:

#!/usr/bin/env python
from datetime import datetime, timedelta

utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=1437323953822)
utc_offset = timedelta(milliseconds=-14400000)
local_time = utc_time + utc_offset
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)

Python always expects POSIX Epoch and therefore it is ok to hardcode it. The explicit formula may be more precise (no rounding error) and it may accept a wider range of input timestamps (fromtimestamp() range depends on platform and may be narrower than the corresponding datetime range).

like image 29
jfs Avatar answered Sep 29 '22 14:09

jfs