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 solution and without reinventing the wheel, I came across time, date, and timedelta. But these seem too inflexible for me so I’m looking for ideas and tips on how to solve this problem using python’s built-in functions – if possible. Here’s the problem: Binning satellite data from swaths to regular grid involves lots of simple time calculations. If I have the date integer: 200702100700 I want to add and subtract hours and minutes from such a time format such that date – 18 would give me a new date that takes into account leap year and can go cross, year, month, day backwards and forwards. Here’s what I understand of python’s datetime package:
from datetime import timedelta, date, time
t1 = date(2007,01,01); t = time(12,0); t2 = datetime.combine(t1,t)
t3 = timedelta(hours=18); t4 = t2 - t3; t5 = t2 + t3
print t4
>>>datetime.timedelta(2006, 23401, 3001)
This time is not very useable in a script that will do thousands of calculations. My problem is that t4 has no year, month, or day objects, and 2006 seems to be treated as hours. It’s all very confusing. Is this possible in python/numpy/scipy? If so, can someone give me a tip?
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.
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.