In this example, you will learn to convert string to datetime.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using datetime module
from datetime import datetime my_date_string = "Mar 11 2011 11:31AM" datetime_object = datetime.strptime(my_date_string, '%b %d %Y %I:%M%p') print(type(datetime_object)) print(datetime_object)
Output
<class 'datetime.datetime'> 2011-03-11 11:31:00
Using strptime(), date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier.
One advantage of converting to date format is one can select the month or date or time individually.
If you want to learn more about the directives and strptime(), please go to Python strptime() – string to datetime object.
2. Example 2: Using dateutil module
from dateutil import parser
date_time = parser.parse("Mar 11 2011 11:31AM")
print(date_time)
print(type(date_time))
Output
2011-03-11 11:31:00 <class 'datetime.datetime'>
Using dateutil module, parse() can be used to convert a string into date time format. The only parameter used is the string.
Related posts:
Python set()
Python enumerate()
Python String find()
Python len()
Python Program to Randomly Select an Element From the List
Python Inheritance
Python Program to Print Colored Text to the Terminal
Python property()
Python ascii()
Python Program to Parse a String to a Float or Int
Python list()
Python next()
Python Modules
Python Closures
How to Get Started With Python?
Python Set difference()
Python Dictionary popitem()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Variables, Constants and Literals
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Functions
Python Program to Find HCF or GCD
Python open()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python oct()
Python Program to Solve Quadratic Equation
Python bytearray()
Python List Comprehension
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python hasattr()
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Sort Words in Alphabetic Order