简体   繁体   中英

Convert integer date format to human readable format

I have a date time format where dates are represented as integers from 1/1/1900 . For example: 1 is 1/1/1900 and 42998 is 20/9/2017.

How can I convert this format to a human readable format like dd/mm/yyyy ? I checked datetime documentation but I did not find any way to do this. I want to do this either on python 3 or 2.7.

Thanks for any suggestion.

You can define your dates as offsets from your basetime and construct a datetime:

In[22]:
import datetime as dt
dt.datetime(1900,1,1) + dt.timedelta(42998)

Out[22]: datetime.datetime(2017, 9, 22, 0, 0)

Once it's a datetime object you can convert this to a str via strftime using whatever format you desire:

In[24]:
(dt.datetime(1900,1,1) + dt.timedelta(42998-1)).strftime('%d/%m/%Y')

Out[24]: '21/09/2017'

So you can define a user func to do this:

In[27]:
def dtToStr(val):
    base = dt.datetime(1900,1,1)
    return (base + dt.timedelta(val-1)).strftime('%d/%m/%Y')
dtToStr(42998)

Out[27]: '21/09/2017'
import datetime

base_date = datetime.datetime(1900, 1, 1)
convert = lambda x: base_date + datetime.timedelta(days=x-1)
>>> convert(42998)
datetime.datetime(2017, 9, 21, 0, 0)

You can use a datetime object to do that.

import datetime
d = datetime.datetime(1900, 1, 1, 0, 0)
d + datetime.timedelta(days = 42998)
>> datetime.datetime(2017, 9, 22, 0, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM