簡體   English   中英

如何在Python中將經過的時間字符串轉換為秒

[英]How to convert elapsed time string to seconds in Python

有誰知道是否有一個“簡單”功能可以將以下經過的時間字符串轉換為秒? 2d1h39m53s

取決於經過了多少時間,並非所有字段都將出現。

我已經看過strptime和datetime,但是如果不為此編寫自己的函數,似乎沒有什么比這更合適的了。 只是想節省時間。 謝謝

我將它寫到幾天前就清楚地驗證了運行時。 在下面的兩個定義之后,只需在要計數的代碼起點處寫“ tic()”,在終點處寫“ toc()”,即可為您提供清晰的時間數據讀取。 希望能幫助到你。

import time
import math


def tic():
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()


def toc():
    if 'startTime_for_tictoc' in globals():
        tf = time.time() - startTime_for_tictoc;
        if tf < 60:
            print("\nElapsed time: %f seconds.\n" % tf)
        elif 60 < tf < 3600:
            mm = math.floor(tf/60)
            ss = tf - (60*mm)
            print("\nElapsed time: %d minute(s) and %f seconds.\n" % (mm, ss))
        elif 3600 < tf < 86400:
            hh = math.floor(tf/3600)
            mm = math.floor((tf-(hh*3600))/60)
            ss = tf - (hh*3600) - (60*mm)
            print("\nElapsed time: %d hour(s) %d minute(s) and %f seconds.\n" % (hh, mm, ss))
        elif tf > 86400:
            dd = math.floor(tf/86400)
            hh = math.floor((tf-(dd*86400))/3600)
            mm = math.floor((tf-(dd*86400)-(hh*3600))/60)
            ss = tf - (86400*dd) - (hh*3600) - (60*mm)
            print("\nElapsed time: %d day(s) %d hour(s) %d minute(s) and %f seconds.\n" % (dd, hh, mm, ss))
    else:
        print("\nToc: start time not set")

不知道那里是否有功能,但這可以完成工作。 同樣適用於“ 2d1h53s”之類的值。

d = []
h = []
m = []
s = []
sd = 0
sh = 0
sm = 0
ss = 0

str = "2d1h39m53s"

i = 0
if str.find("d") > 0:
    i = str.find("d")
    d.append(str[0:i])
    str = str[i:]
if str.find("h") > 0:
    i = str.find("h")
    h.append(str[1:i])
    str = str[i:]
if str.find("m") > 0:
    i = str.find("m")
    m.append(str[1:i])
    str = str[i:]
if str.find("s") > 0:
    i = str.find("s")
    s.append(str[1:i])
    str = str[i:]

try:
    sd = float(d[0]) * 24 * 60 * 60
except:
    sd = 0
try:
    sh = float(h[0]) * 60 * 60
except:
    sh = 0
try:
    sm = float(m[0]) * 60
except:
    sm = 0
try:
    ss = float(s[0])
except:
    ss = 0

print("seconds")
sec = sd + sh + sm + ss
print(sec)

如果您的日期時間具有給定的格式,則可以執行以下操作:

import re
import numpy as np
from functools import reduce

split_strings = ['D', 'h','m','s']
def datestring_to_seconds(datestring):
    values_and_units = [(int(string[:-1]), string[-1]) for string in [re.search(f"([0-9]+){split_string}", 
                            f"{datestring}".replace('d', 'D')).group(0) for split_string in split_strings]]
    return reduce(lambda x,y : x+y, [np.timedelta64(*x) for x in values_and_units])/np.timedelta64(1, 's')

結果

datestring_to_seconds("2d1h39m53s")
178793.0

一些解釋:首先在字符串中搜索任何一個,最多匹配一個split_strings (例如39m )前面的兩位,然后將其轉換為元組(39, "m") 我們對split_strings每個字符串執行此操作,並將結果保存在列表values_and_units ,在我們的特殊情況下,看起來像這樣:

[(2, 'D'), (1, 'h'), (39, 'm'), (53, 's')]

現在,這些元素的每個元素都可以強制轉換為numpy timedelta64。 reduce操作將所有時間增量相加,然后除以np.timedelta64(1, 's')得到具有所需秒數的浮點數。

這是一個純python解決方案。

import re

s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}

secs = 0
m = re.match(r'(\d+)([dhms])', s)

while m is not None:
    secs += int(m.group(1)) * d[m.group(2)]
    s = re.sub(r'\d+[dhms]', '', s, 1)
    m = re.match(r'(\d+)([dhms])', s)

print(secs)


print(secs)

印刷:178793

編輯:使用match.end()定位下一個搜索的開始。 不會破壞字符串s和更干凈的解決方案。

import re

s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}

secs = 0
pat = re.compile('(\d+)([dhms])')

m = pat.search(s)

while m is not None:
    pos = m.end()
    secs += int(m.group(1)) * d[m.group(2)]
    m = pat.search(s, pos)

print(secs)

暫無
暫無

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

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