簡體   English   中英

從python中的數字轉換為hh:mm:ss

[英]converting to hh:mm:ss from numbers in python

我有一列數據位於這樣的數據框中,這些是小時,但它們並不都包含相同的位數

0, 600, 1200, 1800, 0, 600, 等等.....

我想將其更改為 hh:mm:ss 格式。 我該怎么做呢?

干杯

datetime是您的朋友和盟友。

import datetime


lst = [0, 600, 1200, 1800, 0, 600]

lst = [datetime.time(hour=x//100).strftime("%H:%M:%S") for x in lst]
# -> ['00:00:00', '06:00:00', '12:00:00', '18:00:00', '00:00:00', '06:00:00']

熊貓版本,使用 zfill 和 wrap:

import pandas as pd

df = pd.DataFrame({'time': [0, 600, 1200, 1800, 0, 600]})

# fill with zeros to always get 4 digits
# split into two parts, with : inbetween
# add the seconds as ':00'
df['hms'] = df['time'].astype(str).str.zfill(4).str.wrap(2).str.replace('\n', ':') + ':00'

df['hms']
0    00:00:00
1    06:00:00
2    12:00:00
3    18:00:00
4    00:00:00
5    06:00:00
Name: hms, dtype: object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM