Search code examples
pythondatetimetype-conversiontuplestimedelta

convert datetime type to tuple in python


Is there any one liner method to convert datetime to simple tuple

>>> from datetime import datetime, timedelta
>>> new_date = datetime. today() + timedelta(12)
>>> new_date
datetime.datetime(2020, 5, 26, 13, 31, 36, 838650)

How do I convert new_date to tuple type.

This is what I have tried

tuple(new_date)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    tuple(new_date)
TypeError: 'datetime.datetime' object is not iterable

Expected output :

>> (2020, 5, 26, 13, 31, 36, 838650)

Solution

  • If you want to "customize" the output (e.g. including microseconds), you could use attrgetter from the operator module to get the attributes from the datetime object.

    from datetime import datetime
    from operator import attrgetter
    
    attrs = ('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond')
    
    d = datetime.now()
    # datetime.datetime(2020, 5, 14, 12, 49, 35, 33067)
    
    d_tuple = attrgetter(*attrs)(d)
    # (2020, 5, 14, 12, 49, 35, 33067)
    

    Otherwise, just use the timetuple() as shown in the other answers (probably more efficient if you can live without microseconds).