The Wayback Machine - http://web.archive.org/web/20240723142857/https://www.geeksforgeeks.org/python-time-strptime-function/
Open In App

Python time strptime() function

Last Updated : 13 Sep, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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)

Here,

  • date_time_string: It is a necessary string parameter where the date to be formatted is provided.
  • directive: This parameter represents the condition for parsing the given string. It is also a necessary parameter.

Directives Table:

The following tables list the supported directives in python.

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
%b  Abbreviated month name Jan, Feb
%m month as a zero padded decimal number 01, 02
%B  Full month name January, February
%y year without century as a zero padded decimal number 99, 00 
%Y year with century as a decimal number 2000, 1999
%H hour(24 hour clock) as a zero padded decimal number 01, 23
%I hour(12 hour clock) as a zero padded decimal number 01, 12
%p locale’s AM or PM AM, PM
%M Minute as a zero padded decimal number 01, 59
%S Second as a zero padded decimal number 01, 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
%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 %

Examples 1: Python string to date

Python3




import time
  
formatted_date = time.strptime(" 02 Dec 1996",
                               " %d %b %Y")
print(formatted_date)


Output:

time.struct_time(tm_year=1996, tm_mon=12, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=337, tm_isdst=-1)

Example 2: Python string to date and time

Python3




import time
  
print(time.strptime("02/12/1996 5:53","%m/%d/%Y %H:%M"))


Output:

time.struct_time(tm_year=1996, tm_mon=2, tm_mday=12, tm_hour=5, tm_min=53, tm_sec=0, tm_wday=0, tm_yday=43, tm_isdst=-1)

Example 3: Value error

In this example, if time directives will not match then occurred error.

Python3




import time as datetime
  
datetime_str = '08/1/18 3:55:6'
  
try:
    datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as e:
    print('ValueError Raised:', e)
  
  
time_str = '25::55::26'
  
try:
    time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
    print('ValueError:', e)


Output:

ValueError Raised: unconverted data remains:  3:55:6
ValueError: time data '25::55::26' does not match format '%H::%M::%S'


Previous Article
Next Article

Similar Reads

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 converted from time_data using this function.H
5 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
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Python | time.time() method
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. Note: The epoch is the point where the time starts, and is platform dependent. On Windows and
2 min read
Python program to find difference between current time and given time
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format. Examples: Input : h1=7, m1=20, h2=9, m2=45 Output : 2 : 25 The current time is 7 : 20 and given
2 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
MoviePy – Changing Image and Time at same time of Video Clip
In this article we will see how we can change display frames and time line of the video file clip in MoviePy at a same time. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. We use fl_image method to alter the display frames and fl_time method to alter the time, although we can do these task
2 min read
Python time.thread_time() Function
Timer objects are used to represent actions that need to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action was actually performed by the interpreter because it
2 min read
Practice Tags :
three90RightbarBannerImg