Elimination
Elimination

Reputation: 2723

parse datetime string to datetime object without setting a format

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

Answers (4)

thethiny
thethiny

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

sagmansercan
sagmansercan

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

jusstol
jusstol

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

Krishna Chaurasia
Krishna Chaurasia

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

Related Questions