开发者

Python time module won't handle year before 1900

开发者 https://www.devze.com 2023-03-17 16:43 出处:网络
I want to convert date of birth from a text file.Let\'s say, I have data fjsffk 1985-01-30开发者_高级运维

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!


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消