对于重型机械,人们通常需要知道机器运行的小时数。我有一个有开始时间和结束时间的数据。每次使用机器时,我计算机器使用的分钟数。这将导致列df['minutes']。
如何将分钟转换为小时?3,346分钟,我应该有55小时46分钟,或55:46。
将此用作一个工作示例:
df = pd.DataFrame(columns = ['minutes'], data =[3346])07:46:
df‘工期’=pd.to_datetime(df‘M’,unit='m').dt.strftime('%H:%M')03 07:46 07:46:
df‘工期’=pd.to_datetime(df‘M’,unit='m').dt.strftime('%d %H:%M')
为什么是三(03)?03 07:46:
def dur_time1( x):x*=60 x= time.gmtime(x) x= time.strftime("%d %H:%M",x)返回x df‘工期’=df‘M’..apply(Dur_time1)2 days 07:46:00:
def dur_time2( x):x*=60 x=timedelta(秒=x)返回x‘工期’=df‘def’.x*=60(Dur_time2)
我可以和这两天一起生活,我可以把这两天分开,乘以24。但这似乎很复杂。但这些解决方案都没有显示55小时46分钟。
发布于 2022-01-02 22:39:46
您可以使用此函数:
def minutes_to_hours(minutes : int):
time = '{}:{}'.format(minutes//60,minutes%60)
return time 输出:
55:46发布于 2022-01-02 22:45:12
divmod也是一种选择:
def minutes_to_hours(minutes: int):
return '{}:{}'.format(*divmod(minutes,60))发布于 2022-01-02 23:54:13
你的结果绝对没有问题。Python做了你想要它做的事情。
案例1:您要求python给出时间组件中的小时和分钟。
df['duration'] = pd.to_datetime(df['minutes'], unit='m').dt.strftime('%H:%M')案例2:您要求python给出时间组件中的天、小时和分钟。
pd.to_datetime(df['minutes'], unit='m').dt.strftime('%d %H:%M')从文档来看,%d做了以下工作;

python是一个C编译器。在C中,tm_mday从1开始查找下一天/前几天。简单地说;
strftime() takes an
argument of data type time_t, which represents calendar time.
When interpreted as an absolute time value, it represents the
number of seconds elapsed since the Epoch, 1970-01-01 00:00:00
+0000 (UTC)在您的示例中,由于在这个时间组件中有55.766667 hours,所以strftime('%d %H:%M')将其解释为3rd day, 7th Hour 46th Minute since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)。如果你把它改为pd.to_datetime(df['minutes'], unit='m').dt.strftime('%d %I:%M'),你就会意识到它用0来代替它。
如果您想要找到确切的时间组件计数,请使用numpy的日期单位
df['minutes'].astype('timedelta64[m]')/60如前所述,numpy的日期时间单位中的时间跨度是64位整数乘以日期或单位长度的范围。这是时间span for ‘D’ (day) is exactly 24 times longer than the time span for ‘h’ (hour),它将分钟转换为精确的时间组件。
https://stackoverflow.com/questions/70560231
复制相似问题