blah238 blah238 - 1 month ago 7
Python Question

How to parse string dates with 2-digit year?

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

yymmdd
where
yy
ranges from 59 to 05 (1959 to 2005). According to the
time
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

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)