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 Operators
Python List insert()
Python Shallow Copy and Deep Copy
Python Tuple index()
Python any()
Python String find()
Python String expandtabs()
Python zip()
Python List sort()
Python String isspace()
Python Program to Trim Whitespace From a String
Python Program to Get the Full Path of the Current Working Directory
Python Program to Parse a String to a Float or Int
Node.js vs Python for Backend Development
Python Set discard()
Python Program to Find Factorial of Number Using Recursion
Python input()
Python String split()
Python String capitalize()
Python setattr()
Python Program to Shuffle Deck of Cards
Python Program to Access Index of a List Using for Loop
Python Program to Reverse a Number
Python Program to Multiply Two Matrices
Python format()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Check Armstrong Number
Python Set update()
Python callable()
Python all()
Python String format_map()
Python Program to Copy a File