使用ctime将字符串转换为秒

时间:2016-03-02 23:11:40

标签: python python-3.x

我必须编写一个函数,使用time.ctime将格式为H:MM:S的字符串转换为秒(并将其转换回时钟。如何在python中执行此操作?

例如:

" 123:00"会产生7380的输出

" 0:01"会产生1

的输出

" 0:00:00"会产生0

的输出

我已经开始使用此代码

def convert_to_seconds(time_as_a_string):
    time = []
    start = 0
    seconds = time.ctime(seconds)
    if seconds >0:

2 个答案:

答案 0 :(得分:1)

无需ctime()

def to_secs(time):
    time = [int(i) for i in time.split(':')][::-1]
    return sum(time[i]*(60**i) for i in range(len(time)))

def to_clock(secs):
    time = ['']*3
    for i in range(2, -1, -1):
        time[i] = str(int(secs/(60**i))).zfill(2)
        secs %= 60**i
    return ':'.join(time[::-1])

assert(to_secs('123:0') == 7380)
assert(to_clock(1) == '00:00:01')

答案 1 :(得分:0)

不使用Ctime:

总是有一种不必要的难以理解的阅读/理解。

def safecast(newtype, value, default=None):
    try:
        return newtype(value)
    except ValueError:
        return default

def theHardWay(timestring):
    count = timestring.count(':')
    if type(timestring) is not str or count > 2:
        return 0
    if count == 0:
        return safecast(int, timestring)
    timelist = timestring.split(":")
    if len(timelist) == 2:
        return safecast(int, timelist[0], 0) * 60 + safecast(int, timelist[1], 0)
    if len(timelist) == 3:
        return safecast(int, timelist[0], 0) * 3600 + safecast(int, timelist[1], 0) * 60 + safecast(int, timelist[2], 0)
    return 0 # should never be touched

assert(theHardWay("123:00") == 7380)
assert(theHardWay("123:ThisShouldNotFail") == 7380)
assert(theHardWay("000:00:1") == 1)
assert(theHardWay("0:00:000") == 0)

然后有一个更容易的方式:

def theEasyWay(timestring):
     return sum([safecast(int, n, 0) * 60**i for i, n in enumerate(timestring.split(":")[::-1])])

assert(theEasyWay("123:00") == 7380)
assert(theEasyWay("123:ThisShouldNotFail") == 7380)
assert(theEasyWay("000:00:1") == 1)
assert(theEasyWay("0:00:000") == 0)