Fiatpanda2000
Fiatpanda2000

Reputation: 1

Converting float into date with Python

I'm currently struggling to understand the documentation of datetime.

I'm scrapping Excel data and with date it is giving me floats and I'd like to reconvert it to have date again.

My date format is hours:seconds and for example I'd like to have

0.586111 --> 14:04:00

0.585417 --> 14:03:00

I tried to use date time.fromtimestamp(0.586111).strftime('%H-%S')To reconvert it to the needed format but the output is '01-00' and I must admit in don't really understand what's going on and so what is wrong.

I know several questions about formatting date into float already have been asked but the other way is much rarer and I believe some people could make it clearer about the use of datetime in that case.

Thank you for your time and I hope that my problem was understandable.

Upvotes: 0

Views: 4351

Answers (2)

001
001

Reputation: 13533

The time is a fraction of a 24 hour period. There may be a built in function to convert that to a time. If not, try this:

def convert_time(t):
    t24 = t * 24
    hours = int(t24)
    # Discard integer part. Ex 14.066664 -> 0.066664
    t24 %= 1
    minutes = int(t24 * 60)
    t24 -= minutes / 60
    seconds = int(t24 * 3600)
    return datetime.time(hours, minutes, seconds)

Output:

>>> convert_time(0.586111).strftime("%H:%M:%S")
'14:03:59'
>>> convert_time(0.585417).strftime("%H:%M:%S")
'14:03:00'

Upvotes: 1

FObersteiner
FObersteiner

Reputation: 25664

your solution with fromtimestamp is actually quite close, but it takes seconds, not fractional days, so convert to those first.

Alternatively, you can add the fractional days as a timedelta to a datetime object.

EX:

from datetime import datetime, timedelta, timezone

sec_per_day = 86400
print(datetime.fromtimestamp(0.586111 * sec_per_day, tz=timezone.utc).strftime('%H:%M:%S'))
# 14:03:59

print((datetime.min + timedelta(days=0.586111)).strftime('%H:%M:%S'))
# 14:03:59

Note: don't forget to set tz to UTC, otherwise your local time's UTC offset might give you unexpected results. If you use datetime.min, time zones did not exist, so no worries there.

Upvotes: 1

Related Questions