Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting timestamps larger than maxint into datetime objects

I have some code for converting some timestamps stored as strings into datetime objects and noticed today exceptions when it converts dates with an int timestamp value greater than the max int.

datetime.datetime.fromtimestamp(2147570047)

for example gives me

ValueError: timestamp out of range for platform time_t

How can I get around this problem? assuming that I want to stay on 32-bit python (running 2.7.2)

I noticed I can convert the max int into the datetime object then add on any extra with timedeltas but I couldn't think of a particularly efficient or nice way of doing this in practice. What's a good way I can convert these 2038+ timestamps into datetime objects?

like image 589
GP89 Avatar asked May 14 '12 17:05

GP89


1 Answers

Think i worked it out, and I was kinda surprised that this doesn't throw the same exception

>>> datetime.datetime.fromtimestamp(0) + datetime.timedelta(seconds=2147570047)
datetime.datetime(2038, 1, 20, 4, 14, 7)

EDIT: This isn't a perfect solution, seems to be a bit of issues with time zones (I'm currently on BST time (+1) so might explain why this below is an hour apart)

>>> datetime.datetime.fromtimestamp(2047570047)
datetime.datetime(2034, 11, 19, 17, 27, 27)
>>> datetime.datetime.fromtimestamp(0) + datetime.timedelta(seconds=2047570047)
datetime.datetime(2034, 11, 19, 18, 27, 27)
like image 72
GP89 Avatar answered Sep 18 '22 14:09

GP89