Python timedelta对象strfdelta和deltafstr函数,用于转换timedelta>string>timed

2024-09-30 06:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

Python是否有一个strfdelta()deltafstr()函数的实现,类似于^{}^{}对象上的工作方式?在

在这方面也有类似的问题。。。在

。。。但是没有一致的方法可以在两种格式之间来回转换。在

我希望能够从^{}转换为^{},然后再转换回timedelta。在

预期用途是用于hadoopmapper/reducer进程(从mapper脚本输出的中间增量时间,用于输入到reducer脚本中)。在


Tags: to对象函数from脚本stringobject方式
1条回答
网友
1楼 · 发布于 2024-09-30 06:21:39

在搜索了这些函数之后,由于找不到来回转换的函数,我编写了以下两个函数,并将它们包含在脚本中。这与pythonv2.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对象的构造函数参数可以更改以测试不同的场景:

^{pr2}$

相关问题 更多 >

    热门问题