Python convert datetime.time to arrow

8.9k Views Asked by At

I need to convert a python object datetime.time to an arrow object.

y = datetime.time()
>>> y
datetime.time(0, 0)
>>> arrow.get(y)

TypeError: Can't parse single argument type of '<type 'datetime.time'>'
3

There are 3 best solutions below

0
On BEST ANSWER

You can use the strptime class method of the arrow.Arrow class and apply the appropriate formattting:

y = datetime.time()
print(arrow.Arrow.strptime(y.isoformat(), '%H:%M:%S'))
# 1900-01-01T00:00:00+00:00

However, you'll notice the date value is default, so you're probably better off parsing a datetime object instead of a time object.

0
On

A datetime.time object holds "An idealized time, independent of any particular day". Arrow objects cannot represent this kind of partial information, so you have to first "fill it out" with either today's date or some other date.

from datetime import time, date, datetime
t = time(12, 34)
a = arrow.get(datetime.combine(date.today(), t))  # <Arrow [2019-11-14T12:34:00+00:00]>
a = arrow.get(datetime.combine(date(1970, 1, 1), t))  # <Arrow [1970-01-01T12:34:00+00:00]>
0
On

Arrow follows a specific format, as specified in its documentation:

arrow.get('2013-05-11T21:23:58.970460+00:00')  

you need to convert your datetime object to arrow-understandable format in order to be able to convert it to an arrow object. the codeblock below should work:

from datetime import datetime
import arrow

arrow.get(datetime.now())