Open In App

Python DateTime – strptime() Function

Last Updated : 06 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 format
  • format_data is the data present in datetime format which is converted from time_data using this function.

How strptime() works?

This function takes two arguments, a string in which some time is given and a format code, to change the string into, the string is changed to the DateTime object as per the list of codes given below.

Format codes

format code meaning example
%a Abbreviated weekday name Sun, Mon
%A Full weekday name  Sunday, Monday
%w Weekday as decimal number 0…6
%d Day of the month as a zero-padded decimal 01, 02
%-d day of the month as decimal number 1, 2..
%b  Abbreviated month name Jan, Feb
%m month as a zero padded decimal number 01, 02
%-m month as a decimal number 1, 2
%B  Full month name January, February
%y year without century as a zero padded decimal number 99, 00 
%-y year without century as a decimal number 0, 99
%Y year with century as a decimal number 2000, 1999
%H hour(24 hour clock) as a zero padded decimal number 01, 23
%-H hour(24 hour clock) as a decimal number 1, 23
%I hour(12 hour clock) as a zero padded decimal number 01, 12
%-I hour(12 hour clock) as a decimal number 1, 12
%p locale’s AM or PM AM, PM
%M Minute as a zero padded decimal number 01, 59
%-M Minute as a decimal number 1, 59
%S Second as a zero padded decimal number 01, 59
%-S Second as a decimal number 1, 59
%f microsecond as a decimal number, zero padded on the left side 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, 365
%-j day of the year as a decimal number 1, 365
%U Week number of the year (Sunday being the first) 0, 6
%W Week number of the year 00, 53
%c locale’s appropriate date and time representation Mon Sep 30 07:06:05 2013
%x locale’s appropriate date representation 11/30/98
%X locale’s appropriate time representation 10:03:43
%% A literal ‘%’ character %

Example 1: Python program to read datetime and get all time data using strptime. Here we are going to take time data in the string format and going to extract hours, minutes, seconds, and milliseconds

Python3




# import datetime module from datetime
from datetime import datetime
 
# consider the time stamp in string format
# DD/MM/YY H:M:S.micros
time_data = "25/05/99 02:35:5.523"
 
# format the string in the given format :
# day/month/year hours/minutes/seconds-micro
# seconds
format_data = "%d/%m/%y %H:%M:%S.%f"
 
# Using strptime with datetime we will format
# string into datetime
date = datetime.strptime(time_data, format_data)
 
# display milli second
print(date.microsecond)
 
# display hour
print(date.hour)
 
# display minute
print(date.minute)
 
# display second
print(date.second)
 
# display date
print(date)


Output:

523000

2

35

5

1999-05-25 02:35:05.523000

Example 2: Python code that uses strptime. Here we are going to take time data in the string format and going to extract the time stamp in “%d/%m/%y %H:%M:%S.%f” format.

Python3




# import datetime module from datetime
from datetime import datetime
 
# consider the time stamps from a list  in string
# format DD/MM/YY H:M:S.micros
time_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003",
             "27/05/99 07:35:5.523", "28/05/99 05:15:55.523"]
 
# format the string in the given format : day/month/year 
# hours/minutes/seconds-micro seconds
format_data = "%d/%m/%y %H:%M:%S.%f"
 
# Using strptime with datetime we will format string
# into datetime
for i in time_data:
    print(datetime.strptime(i, format_data))


Output:

1999-05-25 02:35:08.023000

1999-05-26 12:45:00.003000

1999-05-27 07:35:05.523000

1999-05-28 05:15:55.523000

we can get the time that follows a structure with all dates by using strptime() itself. 

Syntax:

time.strptime(Timestamp, ‘%d/%m/%y %H:%M:%S’)

where Timestamp includes time and date

Example: Python code to get time in structure:

Python3




#import time
import time
 
# get data of 4 th april 2021  at time 9 pm
print(time.strptime('04/04/21 09:31:22', '%d/%m/%y %H:%M:%S'))
 
# get data of 5 th april 2021  at time 9 pm
print(time.strptime('05/04/21 09:00:42', '%d/%m/%y %H:%M:%S'))
 
# get data of 6 th april 2021  at time 9 pm
print(time.strptime('06/04/21 09:11:42', '%d/%m/%y %H:%M:%S'))
 
# get data of 7 th april 2021  at time 9 pm
print(time.strptime('07/04/21 09:41:12', '%d/%m/%y %H:%M:%S'))


Output:

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=4, tm_hour=9, tm_min=31, tm_sec=22, tm_wday=6, tm_yday=94, tm_isdst=-1)

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=5, tm_hour=9, tm_min=0, tm_sec=42, tm_wday=0, tm_yday=95, tm_isdst=-1)

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=6, tm_hour=9, tm_min=11, tm_sec=42, tm_wday=1, tm_yday=96, tm_isdst=-1)

time.struct_time(tm_year=2021, tm_mon=4, tm_mday=7, tm_hour=9, tm_min=41, tm_sec=12, tm_wday=2, tm_yday=97, tm_isdst=-1)

It is also possible to get the string datetime in yyyy-mm-dd datetime format. yyyy-mm-dd stands for year-month-day. We can convert string format to DateTime by using the strptime() function. We will use the  ‘%Y/%m/%d’  format to get the string to datetime.

Syntax: datetime.datetime.strptime(input,format)

Parameter:

  • input is the string datetime
  • format is the format – ‘yyyy-mm-dd’
  • datetime is the module

For this first, the module is imported and the input DateTime string is given. Now use strptime to get the required format and get the date from DateTime using date() function

Example 1: Python program to convert string datetime format to datetime

Python3




# import the datetime module
import datetime
 
# datetime in string format for may 25 1999
input = '2021/05/25'
 
# format
format = '%Y/%m/%d'
 
# convert from string format to datetime format
datetime = datetime.datetime.strptime(input, format)
 
# get the date from the datetime using date()
# function
print(datetime.date())


Output:

2021-05-25

Example 2: Convert list of string datetime to datetime

Python3




# import the datetime module
import datetime
 
# datetime in string format for list of dates
input = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4']
 
# format
format = '%Y/%m/%d'
for i in input:
   
    # convert from string format to datetime format
    # and get the date
    print(datetime.datetime.strptime(i, format).date())


Output:

2021-05-25

2020-05-25

2019-02-15

1999-02-04

We can also display DateTime in “%d/%m/%Y %H:%M:%S” Format. For this, we are going to get the data in date-month-year hours:minutes;seconds format. So we have to take input datetime string and get this format

Syntax: datetime.strptime(input_date, “%d/%m/%Y %H:%M:%S”)

Parameter:

  • datetime is the module
  • input_date is the string datetime format
  • strptime is used to convert input_date string into datetime

Example 3: Python program to get the string datetime into “%d/%m/%Y %H:%M:%S” Format

Python3




#import datetime
from datetime import datetime
 
# consider the datetime string in dd/mm/yyyy
# hh:mm:ss format
date = "25/05/2021 02:35:15"
 
# convert string datetime to  dd/mm/yyyy hh:mm:ss
# format
datetime_date = datetime.strptime(date, "%d/%m/%Y %H:%M:%S")
print(datetime_date)


Output:

2021-05-25 02:35:15



Previous Article
Next Article

Similar Reads

Python time strptime() function
The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives. Syntax: time.strptime(date_time_srting,directive
2 min read
How to use strptime with milliseconds in Python
strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime objectformat string used to parse the string. These two string arguments are mandatory for converting a string into DateTime object. Syntax: strptime(date_string, format_str
2 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Python | datetime.timedelta() function
Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Ret
2 min read
isocalendar() Function Of Datetime.date Class In Python
The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 full weeks.ISO years do not have any fractional weeks
2 min read
fromtimestamp() Function Of Datetime.date Class In Python
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method. Syntax: @classmethod fromtimestamp(timestamp) Parameters: This fun
2 min read
ctime() Function Of Datetime.date Class In Python
The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character length.Week is printed as a three-letter word.Sun, M
2 min read
Article Tags :
Practice Tags :