The package dateutil provides powerful extensions to datetime
module with expanded time zone and parsing support.
(1) dateutil.parser
import datetime
import dateutil.parser
# http://stackoverflow.com/questions/40806730/how-to-convert-a-timedelta-to-a-string-and-back-again/40808470#40808470
td = datetime.timedelta(days=200, hours=2, minutes=2, seconds=2, microseconds=2)
# Part 1: timedelta to string
dt = datetime.datetime.today() - td
print(dt)
s = str(dt) # 2:00:00
print(s)
# Part 2: string to timedelta
# datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
dt = dateutil.parser.parse(s)
print('dt', dt)
# Get total days: datetime.date(year, month, day)
days = (datetime.date.today() - datetime.date(year=dt.year, month=dt.month, day=dt.day)).days
# datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
td2 = datetime.timedelta( days=days,
hours=dt.hour,
minutes=dt.minute,
seconds=dt.second,
microseconds=dt.microsecond)
print(td2)
print('********')
dt = datetime.datetime(year=2016, month=11, day=25, hour=18, minute=45, second=18)
# Get total days: datetime.date(year, month, day)
days = (datetime.date.today() - datetime.date(year=dt.year, month=dt.month, day=dt.day)).days
td = datetime.timedelta( days=days,
hours=dt.hour,
minutes=dt.minute,
seconds=dt.second,
microseconds=dt.microsecond)
print(td)
(2) relativedelta
and timedelta
The differences between the singular and plural argument in dateutil.relativedelta.relativedelta
?
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.now()
>>> str(now)
'2016-05-23 22:32:48.427269'
>>> singular = relativedelta(month=3)
>>> plural = relativedelta(months=3)
# subtracting
>>> str(now - singular) # replace the corresponding value in the original datetime with the value(s) in relativedelta
'2016-03-23 22:32:48.427269'
>>> str(now - plural) # perform the corresponding aritmetic operation on the original datetime value with the information in the relativedelta.
'2016-02-23 22:32:48.427269'
# adding
>>> str(now + singular) # replace the corresponding value in the original datetime with the value(s) in relativedelta
'2016-03-23 22:32:48.427269'
>>> str(now + plural) # perform the corresponding aritmetic operation on the original datetime value with the information in the relativedelta.
'2016-08-23 22:32:48.427269'
References: