Forhad
Forhad

Reputation: 43

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!

Upvotes: 4

Views: 6788

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

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)

Upvotes: 8

Raceyman
Raceyman

Reputation: 1354

Here is a previous post that may have some ideas for you: formatting-date-string-in-python-for-dates-prior-to-1900

Upvotes: 0

Related Questions