Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python time module won't handle year before 1900

I want to convert date of birth from a text file.Let's say, I have data

fjsffk 1985-01-30
fkgskgks 1899-02-20

I have tried with the following code, still getting error:

import datetime

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']
with open('file.txt', 'r') as f:
    for line in f.readlines():
        dob = line.rsplit(None, 1)[-1]  
        dt = datetime.strptime(dob, "%Y-%m-%d")          
        print "{0:} {1:}, {2:}".format(months[dt.month-1], dt.day, dt.year)

Any solution please, thanks!

like image 609
Forhad Avatar asked Sep 02 '25 15:09

Forhad


1 Answers

As per python tutorial

The exact range of years for which strftime() works also varies across platforms. Regardless of platform, years before 1900 cannot be used.

Please bear with me - i have tried the following solution and it works fine for me:

from datetime import datetime

mDt = datetime(1900,01,01)
dt = datetime.strptime('20-02-1899', "%d-%m-%Y")
resultString = datetime(dt.year + (mDt - dt).days/365 + 1, dt.month, dt.day).strftime('%B %d, %Y').replace('1900', str(dt.year))

OR something like this:

monthes = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
dt = datetime.strptime('20-02-1890', "%d-%m-%Y")
print "{0:} {1:}, {2:}".format(monthes[dt.month-1], dt.day, dt.year)
like image 124
Artsiom Rudzenka Avatar answered Sep 05 '25 05:09

Artsiom Rudzenka