Newbie... Help with Dates/Times

Alex Martelli aleaxit at yahoo.com
Mon Jul 9 03:25:19 EDT 2001


"Drake" <yeahoo at yeehaa.com> wrote in message
news:11f492f.0107082013.e9845f4 at posting.google.com...
    ...
> - Compare file dates (time is irrelevant) of matching files to a
> target date determined by user.
> - If filedate is >= (equal to or after) the target date, the fully
> qualified path prints to a file.
>
> Currently, I'm using an os.path.walk routine to gather the files per
> drive.
>
> Here's my problem...
> Im lost on the date stuff.
>
> 1) I'm thinking of comparing seconds... os.path.getmtime('myfile').
> How do I strip off the time and get the seconds based on only the
> date?

See standard module time.  For example, time.gmtime(x) will give
you a tuple representing the various components of time represented
by seconds x: year, month, day, etc.

Presumably you want to represent a date by one specific instant in
that date, say midnight.  Then you do not need to "strip off the time"
for comparison: you just compare the seconds.

> 2) How do I get the seconds for the target date. The user is entering
> a date. Do I create a time tuple and then convert that to seconds?

Again, module time can help, depending on the string format
you want to be able to accept from the user.  Unfortunately,
function strptime is not supplied by module time on Windows
(there are Python implementations around aplenty, though),
or you can look at separately distributed module mxDateTime
which has other time-parsing functionality.

But if (e.g.) the user is entering a date in a standard format
such as 'yyyy-mm-dd', parsing it in Python is not hard either:
you can date.split('-') and get the three string fields yyyy, mm,
dd, each of which is turned into an int with function int().
time.mktime() accepts the time tuple as the argument (just
be sure to append enough 0's:-) and returns the seconds.

For example:

>>> timestring='2001-06-01'
>>> pieces=timestring.split('-')
>>> pieces
['2001', '06', '01']
>>> timetup=tuple(map(int,pieces))+(0,)*6
>>> timetup
(2001, 6, 1, 0, 0, 0, 0, 0, 0)
>>> x=time.mktime(timetup)
>>> x
991350000.0
>>> time.localtime(x)
(2001, 6, 1, 1, 0, 0, 4, 152, 1)
>>> time.asctime(timetup)
'Mon Jun 01 00:00:00 2001'


Alex






More information about the Python-list mailing list