traggatmot
traggatmot

Reputation: 1463

Turn number representing total minutes into a datetime object in python

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

Answers (3)

Mauro Baraldi
Mauro Baraldi

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

AChampion
AChampion

Reputation: 30288

You may want to look at time deltas:

delta = datetime.timedelta(minutes=360)

Upvotes: 3

Loocid
Loocid

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

Related Questions