2014-03-04 27 views
2

是否存在的strfdelta()deltafstr()功能的Python類似方式的實現,strftime()作品datetime對象?Python的timedelta對象 - 爲timedelta轉換strfdelta和deltafstr功能 - >字符串 - > timedelta

有這個類似的問題...

...但能夠來回在兩種格式之間進行轉換沒有一致的方法。

我希望能夠從timedelta轉換爲string,然後返回到timedelta

預期用途是用於hadoop映射器/縮減器進程(映射器腳本的中間增量時間輸出,用於輸入到reducer腳本中)。

+0

良好問答。我會鼓舞人心的問題,讓別人決定答案是否好。 –

回答

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 "--------"