Reputation: 2723
I have a datetime
string in the following format: 2021-02-25T04:39:55Z
.
Can I parse it to datetime
object without explicitly telling Python how?
strptime()
requires you to set the format.
Upvotes: 0
Views: 798
Reputation: 1258
You can create a new function and call it strptime that calls datetime.strptime:
from datetime import datetime
def strptime(time_, time_fmt=None):
time_fmt = time_fmt or r"Your Own Default Format Here"
return datetime.strptime(time_, time_fmt)
Other than that I prefer if you utilize dateutil
as recommended above.
Upvotes: 1
Reputation: 101
pandas can also be used
import pandas as pd
datetime_str = "2021-02-25T04:39:55Z"
my_datetime = pd.to_datetime(datetime_str).to_pydatetime()
print(my_datetime)
print(type(my_datetime))
# output
# 2021-02-25 04:39:55+00:00
# <class 'datetime.datetime'>
Upvotes: 1
Reputation: 126
You can use dateutil, since your date and time format looks pretty standard.
from dateutil import parser as dtparse
dtparse.parse('2021-02-25T04:39:55Z')
Which returns :
datetime.datetime(2021, 2, 25, 4, 39, 55, tzinfo=tzutc())
Upvotes: 1
Reputation: 9572
You can use the parse
method from dateutil.parser
module which converts a str
object to a datetime object:
from dateutil.parser import parse
dtstr = '2021-02-25T04:39:55Z'
dt = parse(dtstr)
print(dt)
Output:
2021-02-25 04:39:55+00:00
Upvotes: 2