[Tutor] time comparison question

Brian van den Broek bvande at po-box.mcgill.ca
Fri Nov 26 10:45:53 CET 2004

Hi all,

I'm trying to build some Python 2.3.4 code which will determine if the 
actual time when it is run is after the date and time specified in some 
data. I want my data to be able to specify the target date/time in a 
various levels of detail. I.e., I want 2004-11-28 13:25, 2004-11-28, 
11-28, 11-28 13:25 to all be accepted.

My first thought was to get the current time via time.time() and then 
parse my target date into a struct_time tuple to pass to time.mktime(), 
run a comparison and be done. However, a struct_time tuple has data that 
I won't know, given one of my target dates. I can make sensible dummies 
for seconds (as well as year, hours and minutes when my target does not 
specify them), and I know that the time module will try to make a 
reasonable guess if given -1 for the DST element. But for 
a_struct_time_tuple[-3:-1], I'd just be guessing at the weekday and day 
of year. This leads to two questions:

1) As I write, time.asctime() gives 'Fri Nov 26 04:32:18 2004' for a 
time.localtime() of (2004, 11, 26, 4, 32, 18, 4, 331, 0). If I were 
filling out a target date of 2004-11-26 04:32, I might well end up 
passing something like (2004, 11, 26, 4, 32, 18, 6, 328, 0) to 
time.mktime() for the result 'Sun Nov 26 04:32:18 2004'. If I am not 
actually using the weekday information, I suspect that I can just ignore 
the incorrect 'Sun'. But I feel better checking -- is anything going to 
break by giving struct_time elements that don't make sense (provided of 
course I am not myself explicitly drawing upon them)?

2) Naturally, these worries lead me to think that there must be a better 
way. I took a brief look at the datetime module, thinking it was a 
natural place to find such tools. But it is all in terms of classes. 
Sadly, I am still not too comfortable with doing things via OOP, so I'd 
prefer a procedural (if that's the right term for a program with 
functions but no classes) way. Is there a cleaner, non-class employing, 
way of meeting my goal of finding out if a date of the form YYYY-MM-DD 
is in the future, present, or past? (If it matters, I am on Windows.)

Thanks for any links, etc.

Best to all,

Brian vdB

More information about the Tutor mailing list