convert datetime type to tuple in python
Asked Answered
I

3

5

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)
Isocline answered 14/5, 2020 at 8:12 Comment(0)
R
4

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

Rufescent answered 14/5, 2020 at 10:53 Comment(0)
H
2

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.

Hangout answered 14/5, 2020 at 8:16 Comment(0)
F
0

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)
>>> 
Fendig answered 14/5, 2020 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.