【问题标题】:Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta ???? string ???? timedeltaPython timedelta 对象 - strfdelta 和 deltafstr 函数用于转换 timedelta ????细绳 ????时间增量
【发布时间】:2014-03-04 22:21:50
【问题描述】:

是否有类似于strftime() 处理datetime 对象的方式在Python 中实现strfdelta()deltafstr() 函数?

关于这个有类似的问题...

...但没有一致的方式能够在两种格式之间来回转换。

我希望能够从timedelta 转换为string,然后再转换回timedelta

预期用途是用于 Hadoop 映射器/减速器进程(映射器脚本的中间增量时间输出,用于减速器脚本的输入)。

【问题讨论】:

  • 很好的问答。我会投票赞成这个问题,让其他人决定答案是否好。

标签: python type-conversion string-formatting timedelta


【解决方案1】:

在搜索了这样的函数之后,并没有找到一个来回转换的函数,我写了以下两个函数并将它们包含在一个脚本中。这与Python v2.6.6兼容,不支持timedelta.total_seconds()等一些较新的特性:

#!/usr/bin/python

import re
import sys
import datetime

# String from Date/Time Delta:
#  Takes a datetime.timedelta object, and converts the internal values
#  to a dd:HH:mm:ss:ffffff string, prefixed with "-" if the delta is
#  negative
def strfdelta(tdelta):

    # Handle Negative time deltas
    negativeSymbol = ""
    if tdelta < datetime.timedelta(0):
        negativeSymbol = "-"

    # Convert days to seconds, as individual components could
    # possibly both be negative
    tdSeconds = (tdelta.seconds) + (tdelta.days * 86400)

    # Capture +/- state of seconds for later user with milliseonds calculation
    secsNegMultiplier = 1
    if tdSeconds < 0:
        secsNegMultiplier = -1

    # Extract minutes from seconds
    tdMinutes, tdSeconds = divmod(abs(tdSeconds), 60)

    # Extract hours from minutes
    tdHours, tdMinutes = divmod(tdMinutes, 60)
    # Extract days from hours
    tdDays, tdHours = divmod(tdHours, 24)

    # Convert seconds to microseconds, as individual components 
    # could possibly both be negative
    tdMicroseconds = (tdelta.microseconds) + (tdSeconds * 1000000 * secsNegMultiplier)

    # Get seconds and microsecond components
    tdSeconds, tdMicroseconds = divmod( abs(tdMicroseconds), 1000000)

    return "{negSymbol}{days}:{hours:02d}:{minutes:02d}:{seconds:02d}:{microseconds:06d}".format(
        negSymbol=negativeSymbol,
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)


# Date/Time delta from string
# Example: -1:23:32:59:020030 (negative sign optional)
def deltafstr(stringDelta):

    # Regular expression to capture status change events, with groups for date/time, 
    #  instrument ID and state
    regex = re.compile("^(-?)(\d{1,6}):([01]?\d|2[0-3]):([0-5][0-9]):([0-5][0-9]):(\d{6})$",re.UNICODE)
    matchObj = regex.search(stringDelta)

    # If this line doesn't match, return None
    if(matchObj is None):
        return None;

    # Debug - Capture date-time from regular expression 
    # for g in range(0, 7):
    #     print "Grp {grp}: ".format(grp=g) + str(matchObj.group(g)) 

    # Get Seconds multiplier (-ve sign at start)
    secsNegMultiplier = 1
    if matchObj.group(1):
        secsNegMultiplier = -1

    # Get time components
    tdDays = int(matchObj.group(2)) * secsNegMultiplier
    tdHours = int(matchObj.group(3)) * secsNegMultiplier
    tdMinutes = int(matchObj.group(4)) * secsNegMultiplier
    tdSeconds = int(matchObj.group(5)) * secsNegMultiplier
    tdMicroseconds = int(matchObj.group(6)) * secsNegMultiplier

    # Prepare return timedelta
    retTimedelta = datetime.timedelta(
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)

    return retTimedelta;

这里有一些代码可以在两种格式之间来回进行测试。 timedelta 对象的构造函数参数可以更改以测试不同的场景:

# Testing (change the constructor for timedelta to test other cases)
firstDelta = datetime.timedelta(seconds=-1,microseconds=999999, days=-1)
print "--------"
print firstDelta
firstDeltaStr = strfdelta(firstDelta)
print "--------"
print firstDeltaStr;
secondDelta = deltafstr(firstDeltaStr)
print "--------"
print secondDelta
secondDeltaStr = strfdelta(secondDelta)
print "--------"
print secondDelta
print "--------"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多