user11247278
user11247278

Reputation:

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)

Upvotes: 5

Views: 9126

Answers (3)

FObersteiner
FObersteiner

Reputation: 25554

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).

Upvotes: 4

kabanus
kabanus

Reputation: 25895

There is a timetuple you can use.

>>> new_date.timetuple()
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=26, tm_hour=11, tm_min=15, tm_sec=30, tm_wday=1, tm_yday=147, tm_isdst=-1)
>>> tuple(new_date.timetuple())
(2020, 5, 26, 11, 15, 30, 1, 147, -1)

You do not actually need to convert it to a tuple, the above is just to make a point. You can use it where you use a normal tuple.

Upvotes: 2

lenik
lenik

Reputation: 23508

Please, use timetuple() or utctimetuple() for the conversion:

>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2020, 5, 14, 17, 18, 39, 958430)
>>> dt.timetuple()
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=14, tm_hour=17, tm_min=18, tm_sec=39, tm_wday=3, tm_yday=135, tm_isdst=-1)
>>> 

Upvotes: 0

Related Questions