How to Parsing a string into a datetime object?

By Albert, 7 months ago
  • Bookmark
0

How to convert string object into datetime object in python.?

String
Datetime
2 Answers
0

Python 3 .2+ has support for %z format when parsing a string into a datetime object.

import datetime
dt = datetime.datetime.strptime("2021-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")


>dt
datetime.datetime(2021, 4, 15, 8, 27, 18, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))


For other versions of Python, you can use an external library such as dateutil , which makes parsing a string with

timezone into a datetime object is quick.


import dateutil.parser
dt = dateutil.parser.parse("2021-04-15T08:27:18-0500")


The dt variable is now a datetime object with the following value:


datetime.datetime(2021, 4, 15, 8, 27, 18, tzinfo=tzoffset(None, -18000))

0

from datetime import datetime
datetime_string = 'Oct 1 2016, 00:00:00'
datetime_string_format = '%b %d %Y, %H:%M:%S'
datetime.strptime(datetime_string, datetime_string_format)
# datetime.datetime(2016, 10, 1, 0, 0)

Your Answer

Webinars

Live Masterclass on "Python for Artificial Intelligence"

Dec 4th (7:00 PM) 195 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More