Python Date and time

Python strftime()

The date, time, and datetime classes in Python provide a variety of functions for dealing with dates, times, and time intervals. Date and datetime are objects in Python, so when you modify them, you are actually altering objects rather than strings or timestamps. When working with dates or times, you must use the datetime function. This article will teach you how to use the Python strftime() function to convert date, time, and datetime objects to their equivalent strings (with examples).

Python strftime() method

We use the Python strftime() method to convert a datetime to a string. The Python strftime() function is in charge of returning a string representing date and time using a date, time, or datetime object. It accepts one or more lines of formatted code as input and returns the string representation.

The datetime class in Python has a member function called strftime() that can be used to construct a string representation of data in the object. Date and time manipulation classes are provided by the datetime module.

The syntax is as follows:

                    

strftime(format)

Example 1: datetime to string using strftime()

The datetime class in Python has a member method strftime() that creates a string representation of the data in the object, i.e.

                    

datetime.strftime(format_String)

We use datetime.strftime(format_string) to convert a datetime object to a string that matches the format. The format codes are standard directives for specifying the format in which you want to represent datetime.

In this example, we’ll use datetime.now() to get the current time. The datetime.now() returns a datetime.datetime object. Also, we need to first import the datetime module.

Example

                    

from datetime import datetime

now = datetime.now()   # current date and time

year = now.strftime('%Y')
print('Year:', year)

month = now.strftime('%m')
print('Month:', month)

day = now.strftime('%d')
print('Day:', day)

date = now.strftime('%d/%m/%Y')
print('Date:', date)

time = now.strftime('%H:%M:%S')
print('Time:', time)

date_time = now.strftime('%m/%d/%Y, %H:%M:%S')
print('Date and Time:',date_time)

Output

                    

Year: 2021
Month: 10
Day: 20
Date: 20/10/2021
Time: 07:04:16
Date and Time: 10/20/2021, 07:04:16

Format codes in the above program include %d, %m, %Y, and so on. The strftime() method accepts one or more format codes as arguments and returns a formatted text-based on them. The year, month, day, date, time, and date_time are all strings in this case, whereas now is a datetime object.

How strftime() works?

Dates have a standard representation, but you could want to publish them in a different format. The format codes in the above program are %Y, %m, %d, and so on. The strftime() method accepts one or more format codes as arguments and returns a formatted string as a result.

Let us understand how Python strftime() works by looking at one part of the above program.

  • The datetime class was imported from the datetime module. This is due to the fact that the object of the datetime class has access to the strftime() method.
  • In the now variable, a datetime object holding the current date and time is saved.
  • To generate formatted strings, we use the strftime() function.
  • The text passed to the strftime() method can have several format codes. Such as %Y, %y, %h, %d, %p, %s, %M, etc.

Example 2: Creating string from a timestamp

The fromtimestamp() function accepts a timestamp as an argument and returns a datetime object, which we can then use with the strftime() function to extract a day, month, and year from.

                    

from datetime import datetime

timestamp = 1634718429
date_time = datetime.fromtimestamp(timestamp)

print('Date time object:', date_time)

d = date_time.strftime('%m/%d/%Y, %H:%M:%S')
print('Format 2:', d)

d = date_time.strftime('%d %b, %Y')
print('Format 3:', d)

d = date_time.strftime('%d %B, %Y')
print('Format 4:', d)

d = date_time.strftime('%I %p')
print('Format 5:', d)

Output

                    

Date time object: 2021-10-20 08:27:09
Format 2: 10/20/2021, 08:27:09
Format 3: 20 Oct, 2021
Format 4: 20 October, 2021
Format 5: 08 AM

Format Code List

To represent a datetime in a string format, strftime() employs various standard directives. Both the strptime() and strftime() methods use an identical set of directives. The character codes for formatting the date and time are listed below.

Directive

Meaning

Example

%a Weekday as an abbreviated name Sun, Mon, Tue, …
%A Weekday as full name Sunday, Monday, …
%w Weekday expressed as a decimal number 0,1, …, 6
%d Day of the month as a zero-padded decimal number 01, 02, …, 31
%-d Day of the month as a decimal number 1, 2, …, 30
%b Month as an abbreviated name Jan, Feb, …, Dec
%B Month as full 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 2017, 2020, 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 added decimal number. 01, 02, …, 12
%-I Hour (12-hour clock) as a decimal number. 1, 2, … 12
%p Locale’s equivalent of either 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 added 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). 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week). 00, 01, …, 53
%c Locale’s appropriate date and time representation. Mon Oct 30 07:06:05 2021
%x Locale’s appropriate date representation 09/30/21
%X Locale’s appropriate time representation 07:06:05
%% A literal ‘%’ character %

Example 3: Locale’s appropriate date and time

                    

from datetime import datetime

timestamp = 1634730902
date_time = datetime.fromtimestamp(timestamp)

d = date_time.strftime("%c")
print("Output 1:", d)  

d = date_time.strftime("%x")
print("Output 2:", d)

d = date_time.strftime("%X")
print("Output 3:", d)

Output

                    

Output 1: Wed Oct 20 11:55:02 2021
Output 2: 10/20/21
Output 3: 11:55:02

The format codes %c, %x, and %X are used to specify the appropriate date and time for the locale.

Frequently Asked Questions

Q1. What is strftime in Python?

We use the Python strftime() method to convert a datetime to a string. The Python strftime() function is in charge of returning a string representing date and time using a date, time, or datetime object. It accepts one or more lines of formatted code as input and returns the string representation.

The datetime class in Python has a member function called strftime() that can be used to construct a string representation of data in the object. Date and time manipulation classes are provided by the datetime module.

The syntax is as follows:

                    

strftime(format)

Q2. What is ctime in Python?

ctime() in Python converts a time expressed in seconds since the epoch to a string expressing local time. If seconds is not specified or if None is specified, the current time as returned by time() is utilised. The syntax is as follows,

                    

time.ctime([sec])

Example

                    

import time

# seconds passed since epoch
seconds = 1634731296.38228
local_time = time.ctime(seconds)
print('Local time:', local_time)

Output

                    

Local time: Wed Oct 20 12:01:36 2021

Q3. How do I use datetime strftime in Python?

Let us understand how Python strftime() works by looking at one part of the above program.

  • We first import the datetime class from the datetime module. This is due to the fact that the object of the datetime class has access to the strftime() method.
  • In the now variable, a datetime object holding the current date and time is saved.
  • To generate formatted strings, we use the strftime() function.
  • The text passed to the strftime() method can have several format codes. Such as %Y, %y, %h, %d, %p, %s, %M, etc.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.