Chiel
Chiel

Reputation: 6194

Convert date string with days as a float to datetime object

I have a array of floats in Python that look like:

[20010101.0, 20010101.25, 20010101.5, 20010101.75, 20020102.0, ...]

How can I convert this to a datetime object instance taking the decimals properly into account, so that I do not lose the information of the hours?

dat1 = dt.datetime.strptime(str(20010101.25), "%Y%m%d.%f")
print(dat1.date())
print(dat1.hour)

gives, logically:

2001-01-01
0

but I would like it to give:

2001-01-01
6

Upvotes: 2

Views: 3008

Answers (3)

Martin Evans
Martin Evans

Reputation: 46759

You could just convert the hour before passing it to strptime as follows:

from datetime import datetime

dates = [20010101.0, 20010101.25, 20010101.5, 20010101.75, 20020102.0]

for a_date in dates:
    date, hour = divmod(a_date, 1)
    print datetime.strptime('{} {}'.format(int(date), int(24.0 * hour)), "%Y%m%d %H")

Giving you:

2001-01-01 00:00:00
2001-01-01 06:00:00
2001-01-01 12:00:00
2001-01-01 18:00:00
2002-01-02 00:00:00

Upvotes: 2

linpingta
linpingta

Reputation: 2620

I think it's better to process origin data before put it into datetime module, like below:

day, hour = str(20010101.25).split('.')
new_date = day + str(int(float(hour)*24/100))
print datetime.datetime.strptime(new_date, "%Y%m%d%H")

Upvotes: -1

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

There is no direct way,

There are only 4 format specifiers for hours

%H Hour (24-hour clock) as a zero-padded decimal number. 07

%-H Hour (24-hour clock) as a decimal number. (Platform specific) 7

%I Hour (12-hour clock) as a zero-padded decimal number. 07

%-I Hour (12-hour clock) as a decimal number. (Platform specific) 7

You will have to parse hours part yourself and add to datetime object.

Upvotes: 2

Related Questions