Fractional Hours from datetime?

Martin P. Hellwig martin.hellwig at dcuktec.org
Mon Jan 11 08:25:22 EST 2010


Martin P. Hellwig wrote:
> W. eWatson wrote:
>> Maybe there's a more elegant way to do this. I want to express the 
>> result of datetime.datetime.now() in fractional hours.
>>
>> Here's one way.
>>
>> dt=datetime.datetime.now()
>> xtup = dt.timetuple()
>> h = xtup[3]+xtup[4]/60.0+xtup[5]/3600.00+xtup[6]/10**6
>> #  now is in fractions of an hour
> 
> Here is another (though personally I don't find this more elegant than 
> yours, perhaps a bit more readable):
> 
>  >>> now = datetime.datetime.now()
>  >>> fractional_hour = int(now.strftime('%H')) + int(now.strftime('%M')) 
> / 60.0
> 
Actually my version is overcomplicated:
 >>> now = datetime.datetime.now()
 >>> fractional_hour = now.hour + now.minute / 60.0

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'



More information about the Python-list mailing list