blah238 blah238 - 1 year ago 156
Python Question

How to parse string dates with 2-digit year?

I need to parse strings representing 6-digit dates in the format

ranges from 59 to 05 (1959 to 2005). According to the
module docs, Python's default pivot year is 1969 which won't work for me.

Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!

Answer Source

I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:

import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
   dd = dd.replace(year=dd.year-100)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download