Conversion of String to Date Type

Benjamin Niemann pink at odahoda.de
Fri Sep 17 14:38:42 EDT 2004


Keith Bolton wrote:
> Hello All,
> 
> I've joined the wxPython list, but this is my first post on the python
> list and it's good to be here :^)  Anyway...
> 
> My question is relating to Date equality.  I am checking if two string
> representations of dates are less than or equal to eachother. The issue
> that I am having is that the date strings, ex.
> 09/15/04 is evaluated as > 09/14/04.  However, when the last two digits
> for the year are changed, like this 09/15/04  is considered > 09/15/05. 
> I thought this had something to do with evaluating two strings.  Could
> this be the case, if so does someone know of a way to convert those
> strings into a Date type object?
String comparision doesn't know anything about the special semantics of 
dates, and e.g. "09/15/04" is lexically before "10/15/03".
Possible solutions:
- use something like YYYYMMDD, YY/MM/DD... as string representation, 
these will be sorted correctly (which is a good habit anyway, e.g. if 
you have a bunch of files with a date in the filename)
- try "ts = time.mktime(int(s[6:8])+2000, int(s[3:5]), int(s[0:2]))" to 
create timestamps and compare these. The datetime modules may have more 
useful functions (haven't used it yet, time was sufficient for me).
- where do these strings come from? Perhaps there is an underlying 
timestamp or datetime object that you could use instead of "string 
representations".



More information about the Python-list mailing list