Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert seconds to datetime date and time [duplicate]

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'

like image 253
tushariyer Avatar asked Jul 17 '17 09:07

tushariyer


People also ask

How do you convert seconds to HH MM SS in Python?

strftime('%H:%M:%S', time. gmtime(864001)) return a nasty surprise.

How do I convert timestamp to seconds in Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

How do I convert seconds to years in Python?

To convert a second measurement to a year measurement, divide the time by the conversion ratio. The time in years is equal to the seconds divided by 31,556,952.


2 Answers

Like this?

>>> from datetime import datetime >>> datetime.fromtimestamp(1485714600).strftime("%A, %B %d, %Y %I:%M:%S") 'Sunday, January 29, 2017 08:30:00' 
like image 82
Alexander Ejbekov Avatar answered Oct 05 '22 22:10

Alexander Ejbekov


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 
like image 36
Willem Van Onsem Avatar answered Oct 05 '22 22:10

Willem Van Onsem