小时和时间转换为特定格式 [英] Hours and time converting to a certain format
本文介绍了小时和时间转换为特定格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试将以下时间格式 8.25(小数小时)
更改为 8.15 表示 8:15
.而 17.75
到 17.45 表示 17:45
.问题是我特别需要那种格式 (timedelta) e.g 17.45
带有点 .
而不是 :
.
I have been trying to change the following format of time 8.25 (fractional hours)
to 8.15 meaning 8:15
. And 17.75
to 17.45 meaning 17:45
. The problem is that I specifically need that format (timedelta) e.g 17.45
with a point .
instead of :
.
推荐答案
这可以通过使用适当的小数小时表示形式来方便地完成,即 timedelta
.如果输入的数据类型为字符串,则先转换为浮点数.
This can be done conveniently by using the appropriate representation for your fractional hours, namely a timedelta
. If the input is of datatype string, convert to float first.
例如:
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
这篇关于小时和时间转换为特定格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文