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:
Convert a Map to an Array, List or Set in Java
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Convert Kilometers to Miles
Python String isnumeric()
Python Program to Append to a File
Python Program Read a File Line by Line Into a List
Python String isdigit()
Python Shallow Copy and Deep Copy
Python staticmethod()
Convert char to String in Java
Python Program to Reverse a Number
Intelligent Projects Using Python - Santanu Pattanayak
Debug a JavaMail Program
Convert Time to Milliseconds in Java
Python List reverse()
Python Program to Find HCF or GCD
Deep Learning with Python - Francois Chollet
Python Program to Find Numbers Divisible by Another Number
Python __import__()
Python open()
Python String zfill()
Python Operator Overloading
How to Convert List to Map in Java
Python Set difference_update()
Python Errors and Built-in Exceptions
Python String startswith()
Python String upper()
Python type()
Python List insert()
Python str()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Find LCM