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:
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Exception Handling Using try, except and finally statement
Python Program to Find ASCII Value of Character
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python divmod()
Python Program to Remove Punctuations From a String
Python Variables, Constants and Literals
Python String swapcase()
Python String rpartition()
Python Program to Get the File Name From the File Path
Python Matrices and NumPy Arrays
Python List
Python Strings
Python getattr()
Python Program to Transpose a Matrix
Python timestamp to datetime and vice-versa
Python List reverse()
Python frozenset()
Python zip()
Convert char to String in Java
Convert XML to JSON Using Jackson
Python Program to Sort a Dictionary by Value
Python Object Oriented Programming
Python Program to Check If a List is Empty
Python Program to Capitalize the First Character of a String
Python Program to Compute the Power of a Number
Python Program to Shuffle Deck of Cards
Convert String to int or Integer in Java
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python @property decorator
Python Dictionary
Python String join()