简体   繁体   中英

How to convert datetime from decimal to “%y-%m-%d %H:%M:%S” given the time origin?

I did my search around but I couldn't find an answer that satisfies my problem.

I am using python 3.7 and I need to convert a series of decimal numbers into datetime object in the form %Y-%m-%d %H:%M:%S . While doing so I need to consider an origin point, for example:

t = 0.000000 equals to 2016-06-25 00:00:00

t = 0.010417 equals to ..... ?

and so on. I know that in my decimal time the integer part is day since start, decimal part is fraction of day.

I have found an answer using R here . I also think that I might need to use the class method date.fromordinal(ordinal) or something similar but I cannot figure it out how to do it.

This is what I have tried so far:

example t = 1.010416

import datetime as DT
from datetime import timedelta  
day = int(x)
datetime_object = DT.datetime.strptime("2016-06-25 00:00:00", '%Y-%m-%d %H:%M:%S')
python_datetime = DT.datetime.fromordinal(day) + timedelta(days=datetime_object.day-1)

I get:

datetime.datetime(1, 1, 25, 0, 0)

But I cannot add the year 2016 nor the month. Also, for every case in which int(t) = 0 , I get:

ValueError: ordinal must be >= 1

Thank you very much for your answers

Just to leave a clear answer here, taking into account my comments on the other answers:

from datetime import datetime,timedelta

base_date = datetime(2016, 6, 25)
deltas = (2.34857, 0.010417, 1.010416)

for delta in deltas:
    print((base_date + timedelta(delta)).strftime('%Y-%m-%d %H:%M:%S'))

That code yields the following ouput:

>>> from datetime import datetime,timedelta
>>> 
>>> base_date = datetime(2016, 6, 25)
>>> deltas = (2.34857, 0.010417, 1.010416)
>>> 
>>> for delta in deltas:
...     print((base_date + timedelta(delta)).strftime('%Y-%m-%d %H:%M:%S'))
... 
2016-06-27 08:21:56
2016-06-25 00:15:00
2016-06-26 00:14:59
>>> 

timedelta stores its data in this format: (DAYS, SECONDS) so you can calculate it easily:

import datetime

t = 2.34857

# Full days
days = int(t)

# Part of a day
part_of_day = t - int(t)
seconds = int(part_of_day * 24 * 60 * 60)

# Calculate the time delta
dt = datetime.timedelta(
    days=days,
    seconds=seconds
)

# Add t-delta to the first day
first_day = datetime.datetime(2016, 6, 25)
current_time = first_day + dt
current_time

will return:

datetime.datetime(2016, 6, 27, 8, 21, 56)

Then you can convert it to a string with this function:

datetime.datetime.strftime(current_time, '%Y-%m-%d %H:%M:%S')

'2016-06-27 08:21:56'


Edit 1: Instead of constructing the timedelta by days-seconds, one can use just float days as parameter (thanks to accdias!):

dt = datetime.timedelta(days=t)

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