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.

Elimination
  • 2,619
  • 4
  • 22
  • 38
  • 2
    another option: https://stackoverflow.com/a/62769371/10197418 (Python 3.7+). btw. your format is pretty standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). – FObersteiner Feb 25 '21 at 13:06

4 Answers4

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
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
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())
jusstol
  • 126
  • 4
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.

thethiny
  • 1,125
  • 1
  • 10
  • 26
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'>
sagmansercan
  • 101
  • 4