'Python convert datetime.time to arrow
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'>'
Solution 1:[1]
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.
Solution 2:[2]
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())
Solution 3:[3]
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]>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Moses Koledoye |
Solution 2 | Prateek Dewan |
Solution 3 | itsadok |