Javatpoint Logo
Javatpoint Logo

The strftime() function in Python

In this section, we'll learn how the strftime() function in the Python programming language operates as well as some of its variants.

So let's get started.

In order to implement various types of functionalities on the data, Python offers a choice of modules that each contain a cluster of functions. Python's time module is used to implement operations based on different timestamps everywhere.

Additionally, the Python function strftime() accepts times in a variety of formats and outputs a string with the time represented in standard form.

Using Python strftime() function to get the present time

To retrieve the current timestamp in the correct format according to the format codes, we can use the Python strftime() function along with the datetime module.

Python's strftime() function is a powerful tool for working with dates and times in Python. It is used to format the date and time in a specific format. With strftime(), you can easily retrieve the present time in Python in a way that meets your needs.

The basic syntax for using strftime() function is as follows:

Syntax:

Here, the format codes parameter of the strftime() function actually refers to the predefined codes used to represent the timestamp in a standardised and appropriate manner. Throughout this tutorial, we will learn in depth a lot more about the format codes.

Where format is the format string to be used for formatting the date and time, and t is an optional argument that represents the time as a tuple or struct_time object. If t is not provided, the function will use the current local time.

But before that, let us consider examples.

Example:

Output:

Present Time: 16 : 05 : 25
Present Date: 05 - 06 - 2023

Explanation:

We imported the datetime module from the datetime library for the aforementioned example. The current date and time are then stored in a variable that we have specified. The current date and time were then represented using the strftime() function and displayed to the users in the format that was chosen. The current date and time have thus been properly printed in the right and accepted manner.

Example 2:

To get the present time in Python, you can use the %H:%M:%S format string, which will format the time as hours:minutes:seconds. Here's an example of how to use strftime() to get the current time:

In this example, we import the datetime module and use the now() method to get the current date and time. We then pass the current date and time to the strftime() method with the format string %H:%M:%S. Finally, we print the current time.

The output of the above code will be something like this:

Current Time = 14:30:45

As you can see, the strftime() function returns the current time in the specified format. You can change the format string to get the time in different formats. For example, %I:%M:%S %p will return the time in the 12-hour format with AM/PM indicator, while %Y-%m-%d %H:%M:%S will return the time in the ISO 8601 format.

In addition to the time, you can also use strftime() to format the date, weekday, month, and year.

The output of the above code will depend on the current date and time when it is executed. For example, if the code is executed on April 27, 2023, the output might be:

Current Date = 27-04-2023
Today is Thursday
Current month is April
Current year is 2023

Explanation:

The strftime() function is a powerful tool for working with dates and times in Python. By using the right format string, you can easily format the date and time in any way you want.

Using Python strftime() function along with a predefined timestamp

It occasionally occurs when we want to display the date and time of older datasets. The Python strftime() method can be used to carry out the same action.

The datetime module's fromtimestamp() method aids the user in retrieving the predefined timestamp. Additionally, we can use the strftime() function to represent that retrieved timestamp in a common manner utilising the various format codes as previously mentioned.

To use strftime(), you first need to create a datetime object that represents the timestamp you want to format. This can be done using the datetime constructor, which takes arguments for the year, month, day, hour, minute, second, and microsecond. Once you have a datetime object, you can call the strftime() function on it to generate a formatted string.

Python's strftime() function is a powerful tool for formatting dates and times in a way that is both human-readable and machine-readable. It allows developers to convert a timestamp into a formatted string that represents a specific date and time.

The strftime() function is part of Python's datetime module, which is included in the standard library. The function takes a timestamp as an argument and a string that specifies the desired format of the output. The format string can contain various placeholders, each of which represents a specific date or time component. For example, %Y represents the year, %m represents the month, %d represents the day, and so on.

We can see the syntax for the usage of the strftime() function as follows:

Syntax:

Now, let us consider an example illustrating the working of the strftime() function together with a predefined timestamp.

Example:

Output:

Time as per the provided Timestamp: 09 : 15 : 23
Date as per the provided Timestamp: 19 - 08 - 1973

Explanation:

The variable containing the value of the predetermined timestamp was then defined in the aforementioned example. The saved value was then retrieved using the fromtimestamp() technique, and the retrieved timestamp was then represented in a valid and accepted manner using the strftime() function. The users have then seen the final values that we printed. The timestamp has successfully been represented in the correct format as a result.

Using various Format codes with Python strftime() function

Python's strftime() function makes use of many format codes to maintain and standardise the representation of date and time. Additionally, these format codes can be used to display hours, days, weeks, and a lot more separately from the timestamp.

Let us consider an example representing the usage of Format code.

Example:

Output:

Present Day: Tuesday

Explanation:

We imported the strftime function from the time module for the aforementioned example. The strftime() function and the input "%A" are used to create a variable that stores the format code for the current day's local time. The values have then been printed for the user. The programme has consequently printed the complete name of the day.

Now let us consider some more examples using other Format codes.

1. Using "%c" as a format code in order to show the current local time in the following format:

Day Month Date hours:minutes:seconds Year

Example:

Output:

Present Timestamp: Wed Jun  2 16:06:41 2021

Explanation:

In the above program, we have again carried out the equivalent procedure we did earlier. However, we have used "%c" as the format code. As a result, the program has printed the current timestamp in the format code specified above.

2. Using "%R" as a format code in order to represent the time in a 24-hour format.

Example:

Output:

Present Time in 24-hour format: 16:14

Explanation:

We have again followed the same syntax in the above program, but we include the format code "%R" to display the current time in 24-hour format.

3. Using "%r" as a format code in order to represent the time in 12-hour format or Hours:Minutes:Seconds format along with the AM or PM notation.

Example:

Output:

Present Time in 12-hour format: 04:33:12 PM

Explanation:

Similar to what we have done earlier, we have added the "%r" as the parameter for the strftime() function to print the current time in 12-hour format.

4. Using multiple format codes in a single function.

Example:

Output:

Present Timestamp: 06/02/21 -- 16:44:11 PM

Explanation:

To display the date based on the local timestamp, we have used the format code "%x" in the example above. Along with using the format code "%p" to indicate the current time's notation, i.e., AM or PM, we have also used the format code "%X" to display the time in 24-hour format.

There are several format codes available in addition to the ones listed above. This list of format codes includes:

S. No. Format Code Description
1 %a Weekday name in short
2 %A Complete weekday name
3 %b Name of the month in short
4 %B Complete month name
5 %c Chosen date and time representation
6 %C Number of the Century (the year divided by 100, ranging from 00 to 99)
7 %d Month day (ranging from 01 to 31)
8 %D Similar function as %m / %d / %y
9 %e Month day (ranging from 1 to 31)
10 %g Similar function as %G; however, the value is printed without the century
11 %G 4-digit year equivalent to the ISO week number (refer %V)
12 %h Similar function as %b
13 %H Hour, utilizing a 24-hour clock (ranging from 00 to 23)
14 %I Hour, utilizing a 12-hour clock (ranging from 01 to 12)
15 %j Year day (ranging from 001 to 366)
16 %m Month (ranging from 01 to 12)
17 %M Minute
18 %n Newline character
19 %p Either AM or PM as per the provided time value
20 %r Time in AM and PM notation
21 %R Time in 24-hour notation
22 %S Second
23 %t Tab character
24 %T Current time, equal to "%H:%M:%S" format
25 %u Days of Week represented as a number (ranging from 1 to 7) where Monday is considered as 1. Warning: In Sun Solaris Sunday is considered as 1.
26 %U week number of the current year, beginning with the first Sunday as the first day of the first week.
27 %V The ISO 8601-week number of the current year (ranging from 01 to 53), where week 1 is the first week that has at least four days in the current year, and with Monday is considered as the first week day
28 %w Day of the week as a decimal, where Sunday is considered as 0.
29 %W Week number of the current year, beginning with the first Monday as the first day of the first week.
30 %x Chosen depiction of date without the time
31 %X Chosen depiction of time without the date
32 %y The Year lacking a century (ranging from 00 to 99)
33 %Y The Year together with the century
34 %z or %Z Time zone or name or abbreviation
35 %% An actual % character






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA