Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
thornate Avatar asked Sep 22 '26 16:09

thornate


1 Answers

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)
like image 123
eumiro Avatar answered Sep 25 '26 05:09

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!