Reputation: 1463
If I have a number representing a period I am interested in, for example the number 360 representing 360 minutes or 6 hours, how do I turn this into a datetime object such that I can perform the standard datetime object functions on it?
Similarly, if I have a datetime object in the format 00:30:00, representing 30 minutes, how do I turn that into a normal integer variable?
Upvotes: 1
Views: 2440
Reputation: 6575
If your time data is in '00:30:00' format then you should use strptime
>>> from datetime import datetime
>>> time = '00:30:00'
>>> datetime.strptime(time, '%H:%M:%S).time()
datetime.time(0, 30)
If your data is in 30 (integer) format
>>> from datetime import datetime, timedelta
>>> from time import strftime, gmtime
>>> minutes = timedelta(minutes=360)
>>> time = strftime('%H:%M:%S', gmtime(minutes.total_seconds()))
>>> datetime.strptime(time, '%H:%M:%S').time()
datetime.time(6, 0)
Upvotes: 1
Reputation: 30288
You may want to look at time deltas:
delta = datetime.timedelta(minutes=360)
Upvotes: 3
Reputation: 6451
import datetime
t = datetime.timedelta(minutes=360)
This will create an object, t
, that you can use with other datetime objects.
To answer the 2nd question you just edited in, you can use t.total_seconds()
to return whatever your timedelta holds back into an integer in seconds. You'll have to do the conversion to minutes or hours manually though.
Upvotes: 5