[英]How do I convert integer into a time format
我 go 如何將 3.65 之類的浮點數轉換為 4 分 5 秒。
我試過使用:
print(datetime.datetime.strptime('3.35','%M%-S'))
但是,我得到了這個:
ValueError: '-' is a bad directive in format '%-M:%-S'
首先,你應該向那些給你這樣的時間數據的人投訴。
如果您需要將分鍾和秒作為獨立值處理,那么日期時間 object 可能也不是您的最佳選擇。
如果您仍然需要將“3.65”轉換為對應於“4-05”的日期時間 object,您可以在將其傳遞給 strptime() 之前將其調整為有效的時間表示
m,s = map(int,"3.65".split("."))
m,s = (m+s)//60,s%60
dt = datetime.datetime.strptime(f"{m}-{s}","%M%-S")
看看下面的腳本,你可以弄清楚如何讓它工作幾天等等,這只有在我們假設格式是“小時.分鍾”時才有效
import datetime
# Assuming the 3 represents the hours and the 0.65 the minutes
number = 3.65
# First, we need to split the numbero into its whole decimal part
# and its decimal part
whole_decimal_part = hours = int(number) # 3
decimal_part = number % whole_decimal_part # 0.6499999
# Now, we need to know how many extra hours are in the decimal part
extra_hours = round((decimal_part * 100) / 60) # 1
minutes = round((decimal_part * 100) % 60) # 5
hours += extra_hours # 4
time_str = "%(hours)s:%(minutes)s" % {
"hours": hours,
"minutes": minutes
} # 4:5
final_time = datetime.datetime.strptime(time_str, "%H:%M").time()
print(final_time) # 04:05:00
而65秒無法正確解析,只能自己操作,先清理數據再解析。
注意:假設seconds
不是一個非常大的數字,可以使分鍾>60
import datetime
time= '3.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
minute_offset, seconds = divmod(seconds, 60);
minute = int(split_time[0]) + minute_offset
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S')) #1900-01-01 00:04:05
您可以交替使用。 日期時間 object 上的time()
提取時間
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S').time()) #00:04:05
一個更清潔和更安全的解決方案是(也考慮小時)。 將所有內容轉換為秒,然后再轉換回小時、分鍾、秒
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return "%d:%02d:%02d" % (hour, min, sec)
time='59.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
new_seconds = minute*60 +65
datetime.datetime.strptime(convert(new_seconds),'%H:%M:%S').time()
將你的時間分成分鍾和秒 如果秒為 60 或更多,則添加額外的分鍾 (//); 第二個是模數(%)
t="3.65"
m, s = [int(i) for i in t.split('.')]
if s >= 60:
m += s//60
s = s % 60
print(f'{m} mins {s} seconds') # -> 4 mins 5 seconds
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.