0

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.

1

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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'>

1 Comment

pandas uses dateutil's parser internally to infer the format, afaik
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.