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 Program to Reverse a Number
Python Dictionary update()
APIs in Node.js vs Python - A Comparison
Python Set issuperset()
Python Set copy()
Python oct()
Python String upper()
Deep Learning with Python - Francois Chollet
Python globals()
How to Get Started With Python?
Python Program to Check if a Number is Odd or Even
Python bool()
Python Program to Append to a File
Python Strings
Python Program to Copy a File
Python Program to Add Two Matrices
Python Program to Differentiate Between del, remove, and pop on a List
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Get Current time
Python Program to Differentiate Between type() and isinstance()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python hasattr()
Python Program to Check if a Number is Positive, Negative or 0
Python Set difference_update()
Python Set clear()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Check If a String Is a Number (Float)
Python open()
Python isinstance()
Python Program to Shuffle Deck of Cards
Python strptime()
Python Set symmetric_difference_update()