I have a data file containing timestamps like “1331856000000”. Unfortunately, I don’t have a lot of documentation for the format, so I’m not sure how the timestamp is formatted. I’ve tried Python’s standard datetime.fromordinal() and datetime.fromtimestamp() and a few others, but nothing matches. I’m pretty sure that particular number corresponds to the current date (e.g. 2012-3-16), but not much more.
How do I convert this number to a datetime?
datetime.datetime.fromtimestamp()is correct, except you are probably having timestamp in miliseconds (like in JavaScript), butfromtimestamp()expects Unix timestamp, in seconds.Do it like that:
and the result is:
Does it answer your question?
EDIT: jfs correctly suggested in a now-deleted comment to use true division by
1e3(float1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returnsintwhen dividing (using/operator)intbyint(this is called floor division). By replacing the divisor1000(being anint) with the1e3divisor (being representation of1000as float) or withfloat(1000)(or1000.etc.), the division becomes true division. Python 2.x returnsfloatwhen dividingintbyfloat,floatbyint,floatbyfloatetc. And when there is some fractional part in the timestamp passed tofromtimestamp()method, this method’s result also contains information about that fractional part (as the number of microseconds).