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:
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python input()
How to Convert List to Map in Java
Python Anonymous / Lambda Function
Python Tuple
Python Program to Find the Size (Resolution) of a Image
Python __import__()
Python Function Arguments
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python enumerate()
Python Program to Find Hash of File
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Generate a Random Number
Python Program to Calculate the Area of a Triangle
Python Data Types
Python slice()
Python String format()
Python Program to Check Leap Year
Python Dictionary copy()
Python Input, Output and Import
Python Program to Find the Largest Among Three Numbers
Python format()
Python Multiple Inheritance
Convert a Map to an Array, List or Set in Java
Python Program to Iterate Through Two Lists in Parallel
Python Errors and Built-in Exceptions
Python Global Keyword
Convert char to String in Java
Python reversed()
Python Program to Represent enum
Python Type Conversion and Type Casting
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey