Skip to content Skip to sidebar Skip to footer

Working With Time, Date, Timedelta

I have a problem where I work a lot with time and time differences. So far I've solved this using many many if statements but these are error prone. In searching for a better solut

Solution 1:

Gerrat got it right, use the datetime object.

you can create the datetime object fully without creating date and time separately (or using datetime.strptime()).

BUG ALERT Your code and some of the posted responses will inject a hard to see bug.

// this works
datetime(2007,01,01,12)
// this breaks
datetime(2007,01,09,12)

In python, typing the "0" in "09" makes it an octal number ("09" is not valid) when using dates in in your code, avoid the leading zero.


Solution 2:

from datetime import datetime, timedelta, date, time
t2 = datetime(2007, 1, 1, 12, 0, 0); 
t3 = timedelta(hours=18); t4 = t2 - t3; t5 = t2 + t3
print "YEAR", t4.year
print "MONTH", t4.month
print "DAY", t4.day
print "HOUR", t4.hour
print "MINUTE", t4.minute

Running that...

[Mike_Pennington ~]$ python foo.py 
YEAR 2006
MONTH 12
DAY 31
HOUR 18
MINUTE 0
[Mike_Pennington ~]$

Solution 3:

What you want to use is a datetime object, not a date object:

from datetime import datetime, timedelta
t1 = datetime(2007, 01, 01)
print t1 - timedelta(days=18)
>>>datetime.datetime(2006, 12, 14, 0, 0)
print t1 - timedelta(hours=18)
>>>datetime.datetime(2006, 12, 31, 6, 0)

This will work with hours, minutes, and seconds as well!


Post a Comment for "Working With Time, Date, Timedelta"