How to convert timedelta to string and vice versa

The Dateutil object timedeltahas its own method __str__:

In [1]: from datetime import timedelta

In [2]: td = timedelta(hours=2)

In [3]: str(td)
Out[3]: '2:00:00'

What I would like to do is recreate an object timedeltafrom its string representation. However, as far as I can tell, the method datetime.parser.parsewill always return an object datetime.datetime(cf. https://dateutil.readthedocs.io/en/stable/parser.html ):

In [4]: import dateutil.parser

In [5]: dateutil.parser.parse(str(td))
Out[5]: datetime.datetime(2016, 11, 25, 2, 0)

The only way I will do it now is, in the language Convert timedelta to days, hours, and minutes , to get some disgustingly simple (but verbose) math out of me to get seconds, minutes, hours, etc. and transfer them back to a __init__new one timedelta. Or maybe an easier way?

+4
3

pytimeparse, timedelta , , , . , timedelta :

#!/usr/bin/env python3.5
import datetime
import pytimeparse
import unittest

def reconstruct_timedelta(td_string):
    seconds = pytimeparse.parse(td_string)
    return datetime.timedelta(seconds=seconds)

class TestReconstruction(unittest.TestCase):
    def test_reconstruct_timedelta_is_inverse_of_str(self):
        td = datetime.timedelta(weeks=300, days=20, hours=3, minutes=4, milliseconds=254, microseconds=984)
        td_reconstructed = reconstruct_timedelta(str(td))
        self.assertTrue(td == td_reconstructed)

if __name__ == "__main__":
    unittest.main()

, timedelta , , milliseconds microseconds.

+1

datetime.strptime, timedelta.

import datetime

td = datetime.timedelta(hours=2)

# timedelta to string
s = str(td) # 2:00:00

# string to timedelta
t = datetime.datetime.strptime(s,"%H:%M:%S")
td2 = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
+1

? https://docs.python.org/2/library/pickle.html - .

import pickle 

tdi = pickle.dumps(td)

tdo = pickle.loads(tdi) # will have the time delta object 

str(tdo) 
0

Source: https://habr.com/ru/post/1661949/


All Articles