thornate
thornate

Reputation: 5142

Python Epoch Fail with 2-digit year

I'm reading in a set of data files with dates and numbers similar to the following example:

Jan-61  25.3
Feb-61  23.5
Mar-61  37.9
Apr-61  40.6

I'm reading in the dates using

datetime.datetime.strptime(dateVariable, "%b-%y")

Having two-digit years is causing an issue, as numbers less than 70 (i.e. the epoch year) are interpretted as being in the 2000's instead of the 1900's.

It would be very difficult to edit all the files and change the date format. Is there a way to tell datetime to interpret two-digit years differently?

Upvotes: 3

Views: 1197

Answers (2)

ChrisIPowell
ChrisIPowell

Reputation: 494

Years isn't a valid parameter for datetime.timedelta (at least not in Python 2.7), so you'll actually need to use:

dt = datetime.datetime(dt.years - 100, dt.month, dt.day, dt.hours, dt.minutes, dt.seconds)

Upvotes: 0

eumiro
eumiro

Reputation: 213005

You have to draw the thick line somewhere. For instance, if you accept no future dates (i.e. 'Jun-12' is 2012, but 'Aug-12' is 1912):

dt = datetime.datetime.strptime(dateVariable, "%b-%y")
if dt > datetime.now():
    dt = dt - datetime.timedelta(years=100)

Upvotes: 3

Related Questions