Create Python Datetime from string
Last Updated :
02 Nov, 2022
In this article, we are going to see how to create a python DateTime object from a given string.
For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user.
Syntax:
datetime.strptime(date_string, format)
Converting string to DateTime using strptime()
Here we are going to convert a simple string into datetime object, for this we will pass the string into strptime() and objectify the datetime object through this.
Python3
from datetime import datetime
input_str = '21/01/24 11:04:19'
dt_object = datetime.strptime(
input_str, '%d/%m/%y %H:%M:%S')
print("The type of the input date string now is: ",
type(dt_object))
print("The date is", dt_object)
Output:
The type of the input date string now is: <class 'datetime.datetime'>
The date is 2024-01-21 11:04:19
Converting string containing words to datetime using strptime()
The strptime() method allows you to convert timestamps in "words" to date-time objects too. The snippet below shows it can be done:
Python3
from datetime import datetime
time_str = 'May 17 2019 11:33PM'
dt_object = datetime.strptime(
time_str, '%b %d %Y %I:%M%p')
print(dt_object)
Output:
2019-05-17 23:33:00
Python strptime() ValueError
DateTime format for the given string must be known, failing which can cause unnecessary problems and errors. the snippet below shows what problems can be caused:
Python3
from datetime import datetime
time_str = '201123101455'
dt_obj = datetime.strptime(time_str, '%y%m%d%H%M%S')
dt_obj2 = datetime.strptime(time_str, '%d%m%y%H%S%M')
print ("1st interpretation of date from string is: ",dt_obj)
print ("2nd interpretation of date from same string is", dt_obj2)
Output :
1st interpretation of date from string is: 2020-11-23 10:14:55
2nd interpretation of date from same string is 2023-11-20 10:55:14
The strptime() method will not work if the string argument is not consistent with the format parameter. The following snippets show an error occurring due to the mismatch in the format specifier.
Python3
from datetime import datetime
time_str = '220917 114519'
dt_obj = datetime.strptime(time_str, '%d/%m/%y %H:%M:%S')
print ("The type is", type(dt_obj))
print ("The date is", date_time_obj)
Output:
ValueError("time data %r does not match format %r" %(data_string, format))
Format Code List
The format specifiers are mostly the same as for strftime() method. These specifiers are:
Directives | Meaning | Example |
---|
%a | Abbreviated weekday name. | Sun, Mon, ... |
%A | Full weekday name. | Sunday, Monday, ... |
%w | Weekday as a decimal number. | 0, 1, ..., 6 |
%d | Day of the month as a zero-padded decimal. | 01, 02, ..., 31 |
%-d | Day of the month as a decimal number. | 1, 2, ..., 30 |
%b | Abbreviated month name. | Jan, Feb, ..., Dec |
%B | Full month name. | January, February, ... |
%m | Month as a zero-padded decimal number. | 01, 02, ..., 12 |
%-m | Month as a decimal number. | 1, 2, ..., 12 |
%y | Year without century as a zero-padded decimal number. | 00, 01, ..., 99 |
%-y | Year without century as a decimal number. | 0, 1, ..., 99 |
%Y | Year with century as a decimal number. | 2013, 2019 etc. |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 00, 01, ..., 23 |
%-H | Hour (24-hour clock) as a decimal number. | 0, 1, ..., 23 |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, ..., 12 |
%-I | Hour (12-hour clock) as a decimal number. | 1, 2, ... 12 |
%p | Locale’s AM or PM. | AM, PM |
%M | Minute as a zero-padded decimal number. | 00, 01, ..., 59 |
%-M | Minute as a decimal number. | 0, 1, ..., 59 |
%S | Second as a zero-padded decimal number. | 00, 01, ..., 59 |
%-S | Second as a decimal number. | 0, 1, ..., 59 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000 - 999999 |
%z | UTC offset in the form +HHMM or -HHMM. | |
%Z | Time zone name. | |
%j | Day of the year as a zero-padded decimal number. | 001, 002, ..., 366 |
%-j | Day of the year as a decimal number. | 1, 2, ..., 366 |
%U | Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, ..., 53 |
%W | Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, ..., 53 |
%c | Locale’s appropriate date and time representation. | Mon Sep 30 07:06:05 2013 |
%x | Locale’s appropriate date representation. | 09/30/13 |
%% | A literal '%' character. | % |
Similar Reads
Converting string into DateTime in Python The goal is to convert a date string like "2021/05/25" into a Python-recognized DateTime object such as 2021-05-25 00:00:00. This enables accurate and consistent date operations like comparisons, calculations and formatting when working with time-related data from sources like files or user input. L
2 min read
Convert Date To Datetime In Python When you're programming, dealing with dates and times is important, and Python provides tools to manage them well. This article is about changing dates into date times in Python. We'll explore methods that can help you switch between these two types of data. Whether you're building a website or work
3 min read
Get current date using Python Prerequisite: DateTime moduleIn Python, Date and Time are not data types of their own, but a module named DateTime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. The DateTime module provides some functions
3 min read
Python DateTime - strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.Syntax: datetime.strptime(time_data, format_data)Parameter:time_data is the time present in string formatformat_data is the data present in datetime format which is
7 min read
Isoformat to datetime - Python In this article, we are going to see how to convert Isoformat to datetime in Python. Method 1: Using fromisoformat() in datetime module In this method, we are going to use fromisoformat() which converts the string into DateTime object. Syntax:Â datetime.fromisoformatc(date) Example: Converting isofo
1 min read
How to convert datetime to date in Python In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.date f
3 min read
Python - Convert excel serial date to datetime This article will discuss the conversion of an excel serial date to DateTime in Python. The Excel "serial date" format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to
3 min read
Extract time from datetime in Python In this article, we are going to see how to extract time from DateTime in Python. In Python, there is no such type of datatype as DateTime, first, we have to create our data into DateTime format and then we will convert our DateTime data into time. A Python module is used to convert the data into Da
4 min read
Convert string to datetime in Python with timezone Converting a string to a datetime in Python with timezone means parsing a date-time string and creating a timezone-aware datetime object. For example, a string like '2021-09-01 15:27:05.004573 +0530' can be converted to a Python datetime object that accurately represents the date, time and timezone.
2 min read
PHP | Converting string to Date and DateTime Converting the string to Date and DateTime uses several functions/methods like strtotime(), getDate(). We will see what these functions do. strtotime() This is basically a function which returns the number of seconds passed since Jan 1, 1970, just like a linux machine timestamp. It returns the numbe
2 min read