views:

73

answers:

3

I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format

'10-JUL-2010'

then subtract a day (I would use timedelta), and return the string

'09-JUL-2010 00:00:00 ET'

of course, this is for hundreds of dates. While it should be trivial, I cannot find the info on how to read formatted dates in Python 2.3! Help!

Edit

I am able to retrieve the formatted date as a tuple, but it will not accept the timedelta object for subtraction! Still working on it...

** Edit **

Finally... thanks to your help I was able to solve the problem as follows:

print (datetime(*(time.strptime(date_string, format)[0:6])).strftime('%d-%b-%Y')).upper()+'00:00:00 ET'
+2  A: 

You're looking for datetime.datetime.strptime(), but the documentation is awful for that function, it's effectively the reverse operation of datetime.datetime.strftime().

The format string you're looking for is: '%d-%b-%Y'

See: http://www.python.org/doc/2.3.5/lib/node211.html and http://www.python.org/doc/2.3.5/lib/datetime-datetime.html and http://www.python.org/doc/2.3.5/lib/module-time.html

Edit: Oh snap! There is no strptime in the datetime module in python 2.3. It's in the time module, you'll have to use that one instead.

Sufian
Yes, but the `strptime()` function is not available!
Arrieta
It's in the time module, as noted in the edit. That last link will show you the light.
Sufian
Thanks... not I'm trying to get the result of `strptime()` to subtract a `timedelta` object. They're not compatible! this is a nightmare!
Arrieta
Thank you, Sufian, your help with the link from THC4k helped me solved the problem. I will be accepting yours as the answer.
Arrieta
A: 

Well, there is no builtin for that in 2.3, only from 2.5 on. But for that one format you can parse it by hand ...

months = { 'JAN' : 1, 'FEB' : 2, ... } # write that yourself :p
day,mon,year = thedate.split('-')
day = int(day)
mon = months[mon]
year = int(year)
parsed = datetime.datetime(day=day, month=month, year=year)
THC4k
A: 

If strptime() is not working out for you there is also the option of brute forcing it with a regex:

import re
import date
timestamp_regex = re.compile(r"(\d\d)-(\w\w\w)-(\d\d\d\d)")
# month_mapping: a mapping for 3 letter months to integers
d1 = datetime.date(int(match.group(3)),          #year
                   month_mapping[match.group(2)],#month
                   int(match.group(1)))          #day
pokstad