Master Time Formatting with strftime in Python

The strftime() in Python can be used for date and time formatting in a string. It is beneficial when you have to showcase the output in a desirable format.

In this article, we will learn about the strftime() function in Python. We will also learn its format codes and other features. Strftime is a built-in function. It can alter a string based on time or date.

The strftime() function

In Python, you can use the strftime() function to change the date and time that are displayed in a string. The format string specifies the display of the date and time. The format string is a single character that can be passed as a function argument.

For example, %d – displays the day of the month (1-31)%F – displays the day of the week (Sunday-Saturday)%h – displays an abbreviated hour (00-23)%H – displays an abbreviated hour, and minute (00-59), etc.

Applications

In Python, the strftime() function can be used to change a string’s date and time format. This is useful for changing the date and time displayed in your program’s output when running on different platforms.

Working of strftime()

You can pass a date and time string or an integer representing the seconds. Here is an example:

print("The current date and time is " + strftime("%A %B %e %Y",time))

The strftime() function takes a single argument, which must be a string containing a date format specification. Passing an invalid string or value to strftime() will raise an exception with details about what went wrong.

By default, python stores the date and time as datetime objects. Hence, firstly importing the datetime module is necessary.

Convert datetime object in string

Format Specifier Character Codes

  • %d: For the day of the month, from 1 to 31.
  • %m: For the month of the year
  • %Y: For the year in a four-digit format
  • %y: For a year without the 0’s
  • %A: For weekdays. Like, Monday, Tuesday
  • %a: For the short name of the weekday (First three characters.). Like, Mon, Tue
  • %H: For an hour in 24h format.
  • %I: For 12-hour format time.
  • %M: For the minute
  • %S: For the second
  • %f: For the microseconds from 000000 to 999999
  • %p: For a time in AM/PM format
  • %w: For weekdays as a decimal number, 0 is Sunday, and 6 is Saturday.
  • %U: For the week number of the year
  • %W: For the week number of the year

Convert the current date in string format

Use the now() function to obtain the current date and time. Use format specifiers to get desired output.

from datetime import datetime
now = datetime.now()
string_date = now.strftime("%Y-%m-%d %H:%M:%S")
print('DateTime in String format is :', string_date)
#this will give the present date

Change the date’s individual attributes in str format

Using the previous example and importing the datetime module, after implementing the now() function to get the current date, opt for the following piece of code:

now_date = now.strftime("%d/%m/%Y")
now_time = now.strftime("%H:%M:%S")
now_year = now.strftime("%Y")
now_month = now.strftime("%m")
now_day = now.strftime("%d")
#now, print all of them individually 

Change in numerical format

Through this, you can get all the components of the date in the form of numbers.

now_date.strftime("%d-%m-%y %H:%M:%S"))
print("dd-mm-yyyy:", now_date.strftime("%d-%m-%Y"))
print("dd-mm-yy Format:", now_date.strftime("%d-%m-%y"))

Change only date in str format

Earlier, we altered datetime objects. In this example, we will work for the date object specifically.

from datetime import date
today = date.today()
print('Date in String Format is ', today.strftime("%d-%m-%y"))

Alternatively, using the now() function also, you can convert the date to string format with the help of the strftime() function.

today = datetime.now().date() 
# this gives an str type output

Convert time object in a string using the datetime module

You can specifically change the time object in string format too.

from datetime import datetime
present_time = datetime.now().time()
print("24 hours format time is:",
present_time.strftime("%H-%M-%S"))
print("12 hours format time is:", present_time.strftime("%I-%M-%S"))

Change time in Microseconds, AM/PM Format

As mentioned above, use the %f format code to get the output of time in microseconds. Also, the %p format code will change time in AM/PM format

from datetime import datetime
Curr_time = datetime.now().time()
print('Current Time:', Curr_time)
# Represent time in (HH:MM:SS.Microsecond)
print("Time in microseconds format:", Curr_time.strftime("%H:%M:%S.%f"))

dt = datetime.now()
# %p to represent datetime in AM/PM
print("Time is:", dt.strftime("%d-%b-%Y %I.%M %p"))

Convert the time object into a string using the time module

This will consist of 2 arguments- format code, similar to the ones used above, and the time tuple.

import time
time1 = time.time()
# getting local time from current time in seconds
local_time = time.localtime(time1)
print("The time tuple:", local_time)
print('Formatted Time in string format is:', time.strftime("%d/%m/%y %H:%M:%S", local_time))

Changing in integer form

There might be a possibility for you to store the output in int form. For example:

New_time= int(dt.strftime("%Y%m%d%H%M%S"))

Here, the place value corresponding to the year, month, day, etc, is stored collectively.

The same goes for float. To get a floating output, replace int in the above code with float.

Problem with strftime before 1900

This module has adapted its functionality with regard to the older C language version. So, by default, it doesn’t take dates before 1900 as input. You may use the iso format function to separate the date from the time if required.

Time.isoformat(" ")

Using strftime as part of a dataframe

strftime also finds its usage in pandas. You may format a series of data using the format specifiers mentioned above. Make sure that you import pandas before executing this.

print(series.dt.strftime('% d % m % Y'))

Strftime in jinja2

Simply put the given date in double braces if you’re working with jinja2. To get a formatted date, put in the required specifiers, and you’re good to go! This is the easiest method that has been discovered so far.

{{ abc.mydate.strftime('%Y-%m-%d') }}

Strftime vs Strptime

Contrary to strftime, strptime returns a tuple format date. Its syntax is:

Time= time.strptime("1 Jan 00", "%d %b %y")

Strftime zero padding

In case you wish to format the output in such a way that no zeroes are present, this method will work. You can remove zero padding this way or use %m, %d format specifiers:

New_time= new_date.strftime("%Y-%m-%d").replace("-0", "-")
#alternatively, replace -0 with -

FAQs

What is the meaning of f in strftime()?

Here, f stands for formatting.

Conclusion

In this, we learned about the strftime() function and its attributes.

See also:

Different Methods in Python to Calculate Time Difference in Seconds
(Opens in a new browser tab)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments