将日期时间转换为小时数?

Jan*_*oez 6 python time datetime

我有一个日期时间戳(例如time(6,30)),它将返回06:30:00.我想知道如何将其转换为6.5小时.

亲切的问候

Wil*_*sem 4

您可以简单地使用:

import datetime

the_time = datetime.time(6,30)
value = the_time.hour + the_time.minute/60.0
Run Code Online (Sandbox Code Playgroud)

如果您还想考虑几秒或几秒,您可以使用:

import datetime

the_time = datetime.time(6,30)
value = the_time.hour + the_time.minute/60.0 + \
            the_time.second/3600.0 + the_time.microsecond/3600000000.0
Run Code Online (Sandbox Code Playgroud)

两者都在这里生成:

>>> the_time.hour + the_time.minute/60.0
6.5
>>> the_time.hour + the_time.minute/60.0 + \
...             the_time.second/3600.0 + the_time.microsecond/3600000000.0
6.5
Run Code Online (Sandbox Code Playgroud)

或者,如果您想使用后缀打印它'hrs'

import datetime

the_time = datetime.time(6,30)
print('{} hrs'.format(the_time.hour + the_time.minute/60.0))
Run Code Online (Sandbox Code Playgroud)

这将打印:

>>> print('{} hrs'.format(the_time.hour + the_time.minute/60.0))
6.5 hrs
Run Code Online (Sandbox Code Playgroud)