小时和时间转换为特定格式
Hours and time converting to a certain format
我一直在尝试将以下时间格式8.25 (fractional hours)
更改为8.15 meaning 8:15
。并且 17.75
到 17.45 meaning 17:45
。问题是我特别需要带有点 .
而不是 :
.
的格式 (timedelta) e.g 17.45
鉴于您的格式字符串 HH.MM
,您可以按如下方式处理它:
my_time = "17.75"
hours, minutes = my_time.split(".") # (17, 75)
minutes_converted = round(float(minutes) / 100 * 60) # 45
my_time_converted = "{}.{}".format(hours, minutes_converted) #17.45
print(my_time_converted)
> 17.45
这可以通过使用适当的小数小时表示形式方便地完成,即 timedelta
。如果输入数据类型为string,先转换为float。
例如:
from datetime import datetime, timedelta
for td in [8.25, 17.75]:
# add the duration as timedelta to an arbitrary date to get a time object:
print((datetime(2020,1,1) + timedelta(hours=td)).time())
08:15:00
17:45:00
使用pandas
,看起来像
import pandas as pd
s = pd.Series([8.25, 17.75])
refDate = '2020-01-01' # need a date..
t = pd.Timestamp(refDate) + pd.to_timedelta(s, unit='h')
print(t)
# 0 2020-01-01 08:15:00
# 1 2020-01-01 17:45:00
# dtype: datetime64[ns]
print(t.dt.time)
# 0 08:15:00
# 1 17:45:00
# dtype: object
我一直在尝试将以下时间格式8.25 (fractional hours)
更改为8.15 meaning 8:15
。并且 17.75
到 17.45 meaning 17:45
。问题是我特别需要带有点 .
而不是 :
.
e.g 17.45
鉴于您的格式字符串 HH.MM
,您可以按如下方式处理它:
my_time = "17.75"
hours, minutes = my_time.split(".") # (17, 75)
minutes_converted = round(float(minutes) / 100 * 60) # 45
my_time_converted = "{}.{}".format(hours, minutes_converted) #17.45
print(my_time_converted)
> 17.45
这可以通过使用适当的小数小时表示形式方便地完成,即 timedelta
。如果输入数据类型为string,先转换为float。
例如:
from datetime import datetime, timedelta
for td in [8.25, 17.75]:
# add the duration as timedelta to an arbitrary date to get a time object:
print((datetime(2020,1,1) + timedelta(hours=td)).time())
08:15:00
17:45:00
使用pandas
,看起来像
import pandas as pd
s = pd.Series([8.25, 17.75])
refDate = '2020-01-01' # need a date..
t = pd.Timestamp(refDate) + pd.to_timedelta(s, unit='h')
print(t)
# 0 2020-01-01 08:15:00
# 1 2020-01-01 17:45:00
# dtype: datetime64[ns]
print(t.dt.time)
# 0 08:15:00
# 1 17:45:00
# dtype: object