43

How do I convert an int like 1485714600 such that my result ends up being Monday, January 30, 2017 12:00:00 AM?

I've tried using datetime.datetime but it gives me results like '5 days, 13:23:07'

tushariyer
  • 906
  • 1
  • 10
  • 20

2 Answers2

82

Like this?

>>> from datetime import datetime
>>> datetime.fromtimestamp(1485714600).strftime("%A, %B %d, %Y %I:%M:%S")
'Sunday, January 29, 2017 08:30:00'
Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26
  • Indeed! However, in the end I am trying to conduct this operation on a list of seconds, all of which I am trying to convert to the above datetime format. The loop I run keeps giving me an index out of bounds error. Any thoughts? `for j in ts_date: ts_date[j] = datetime.datetime.fromtimestamp(ts_date[j]).strftime("%A, %B %d, %Y %I:%M:%S")` – tushariyer Jul 17 '17 at 09:28
  • @tushariyer need to see your code. – Alexander Ejbekov Jul 17 '17 at 09:29
  • if you are iterating over a list, and trying to modify the value based on the positional key, you should be using the built-in `enumerate` function: `for j, val in enumerate(ts_date):` .. – Alexander Ejbekov Jul 17 '17 at 09:34
17

What you describe here is a (Unix) timestamp (the number of seconds since January 1st, 1970). You can use:

datetime.datetime.fromtimestamp(1485714600)

This will generate:

>>> import datetime
>>> datetime.datetime.fromtimestamp(1485714600)
datetime.datetime(2017, 1, 29, 19, 30)

You can get the name of the day by using .strftime('%A'):

>>> datetime.datetime.fromtimestamp(1485714600).strftime('%A')
'Sunday'

Or you can call weekday() to obtain an integers between 0 and 6 (both inclusive) that maps thus from monday to sunday:

>>> datetime.datetime.fromtimestamp(1485714600).weekday()
6
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555