2

The following code returns '2012-06-07 00:00' for both the timestamp 1339119900000 and 1339120800000:

>>> from datetime import date
>>> date.fromtimestamp(1339119900000/1e3).strftime('%Y-%m-%d %H:%M')
'2012-06-07 00:00'
>>> date.fromtimestamp(1339120800000/1e3).strftime('%Y-%m-%d %H:%M')
'2012-06-07 00:00'

However, these timestamps are 15 minutes apart, and neither of them are exactly midnight.

I'm running 32bit Python 2.7.3 on a Windows 7 machine, but noticed the same on a Red Hat machine. Why is this and how can I get hour and minute resolution from a timestamp?

2 Answers 2

7

You are creating date objects, not datetime. Dates ignore all time information.

Use datetime objects instead if you want to preserve the time component:

>>> from datetime import datetime
>>> datetime.fromtimestamp(1339119900000/1e3).strftime('%Y-%m-%d %H:%M')
'2012-06-08 02:45'
>>> datetime.fromtimestamp(1339120800000/1e3).strftime('%Y-%m-%d %H:%M')
'2012-06-08 03:00'
1

date does not have hours or minutes use datetime.datetime

>>>> datetime.fromtimestamp(1339119900000/1e3).strftime('%Y-%m-%d %H:%M')
'2012-06-08 03:45'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.