Python convert seconds to datetime date and time

Question:

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’

Asked By: tushariyer

||

Answers:

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
Answered By: Willem Van Onsem

Like this?

>>> from datetime import datetime
>>> datetime.fromtimestamp(1485714600).strftime("%A, %B %d, %Y %I:%M:%S")
'Sunday, January 29, 2017 08:30:00'
Answered By: Alexander Ejbekov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.