[Tutor] Copy Files, Dates

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Apr 18 19:08:01 2003


On Fri, 18 Apr 2003, Bob Gailer wrote:

> At 03:55 PM 4/18/2003 -0600, Mike Hansen wrote:
> >[snip]
> >How do you copy files using Python?
>
> Check out the shutil module
>
> >First I need to find out if a string is a Date. Is there any IsDate like
> >function? Also, is there a module that compares dates?
>
> Unfortunately there is no standard format for dates. To ask if a string
> is a date is very vague. Do you have certain formats in mind? Check out
> the time module. There is a strptime function which takes a string and a
> format. You'd probably have to try several formats.


Hi Mike,

The third-party package, 'mxDateTime', has a very nice 'parser' module:

    http://www.egenix.com/files/python/mxDateTime.html



With it, we can cook up an isDate() function that's fairly robust:

###
from mx.DateTime.Parser import DateTimeFromString
def isDate(date_string):
    """A simple test to see if the date_string is parseable as a date."""
    formats = ['euro', 'us', 'altus', 'iso', 'altiso', 'lit',
               'alitlit', 'eurlit']
    try:
        parsed_date = DateTimeFromString(date_string, formats)
        return parsed_date
    except ValueError:
        return 0
###


Let's see how it works:

###
>>> isDate('April 18, 2003')
<DateTime object for '2018-04-01 20:03:00.00' at 8125250>
>>> isDate('Mumbember 18, 2003')
0
###


This isDate() function isn't strictly a boolean function, but since class
instances are True values as far as Python is concerned, I think it's
close enough.  I don't know if this is sufficiently fast or efficient, so
you may need to see if it will perform well for you.


Good luck to you!