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 Global Keyword
Deep Learning in Python - LazyProgrammer
Python Dictionary clear()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python List Comprehension
Python Program to Count the Occurrence of an Item in a List
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Access Index of a List Using for Loop
Python divmod()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Recursion
Python Program to Find ASCII Value of Character
Python Program to Find Numbers Divisible by Another Number
Python List clear()
Python Set difference()
Python Program to Delete an Element From a Dictionary
Python Tuple index()
Python List pop()
Python String expandtabs()
Python Program to Find the Factors of a Number
How to Convert List to Map in Java
Python Program to Find the Factorial of a Number
Python Program to Find Hash of File
Python String rjust()
Python Program to Make a Simple Calculator
Python String partition()
Python delattr()
Python Dictionary get()
Python String isprintable()
Python Errors and Built-in Exceptions
Python Set symmetric_difference_update()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman