strftime(): formats a date or datetime object as a string according to a specified format

strftime() : Returns the string by using format by taking date object as input .

Today's date details using strftime()

from datetime import date
dt = date.today().strftime('%Y-%m-%d')
print(dt)
Output
2019-09-17
Date with time
from datetime import datetime
dt = datetime.now().strftime('%c')
print(dt)
Output
Tue Sep 17 10:51:02 2019

Using date object

import datetime
# Year, Month, date, Hour, Minute, Second, microsecond 
dt = datetime.datetime(2019,12,31,23,59,59,345234)
print(dt.strftime('%Y-%m-%d  %H:%M:%S'))
Output
2019-12-31  23:59:59
Add Microsecond
print(dt.strftime('%Y-%m-%d  %H:%M:%S - %f'))
output
2019-12-31  23:59:59 - 345234

From Database to display as string

We can collect date column value from MySQL or SQLite database and display in any format using the table below. Here dt_column is the date value from table in YYYY-MM-DD format.
dt=datetime.strptime(dt_column,'%Y-%m-%d').strftime('%d-%b-%Y') # sqlite
dt=datetime.strftime(dt_column,'%d-%b-%Y') # MySQL
List of format codes used with strftime()
%aWeekday (short) : Sun, Mon ...
%AWeekday (long ) :Sunday, Monday ...
%wWeekday in decimal : 0,1 ... (Here Sun=0, Mon=1) ...
%dDay of the month with zero padded : 01,02,03 .... 11,12....
%bMonth ( short) : Jan, Feb ...
%BMonth ( Long ) : January , February ...
%mMonth ( number ) : 01,02 ... 11,12
%yYear ( short ) : 01,02 ... 19,20 ...
%YYear ( Long ) : 1998,2013 ...
%HHour ( 24 hour ) : 01,02.. 22,23
%IHour (12 Hour ): 01,02 ..12
%pAM or PM : or am mp ( de_DE).
%MMinutes : 01,02.. 59
%SSeconds : 01,02 .. 59
%fMicrosecond : 000001,000002 .. 999999
%zUTC offset in terms of HHMM ( + or - ) : 0000,-0130,0530..
%ZTime zone name :UTC, CST , EST
%jday of the year ( zero padded ) : 004,121 .. 365
%UWeekday of the Year ( zero padded), Sunday as first day of the week : 00,01,02,03 .. 53
%WWeekday of the Year ( zero padded), Monday as first day of the week : 00,01,02,03 .. 53
%cLocale’s appropriate date and time : Tue Dec 31 23:59:59 2019
%xLocale’s appropriate date : 12/31/19
%XLocale’s appropriate Time : 23:59:59

Using Time

We can get hour, minute and second values and then update to integer by using int() . Using these values we can perform calculations. Use the above formats to get Minute and second values.
import time
h = time.strftime('%I') # getting local hour in 12 hours format as string 
m = time.strftime('%M') # getting local minute as string 
s = int(time.strftime('%S')) # getting local second value as integer using int() 
h = int(h) * 2 # to multiply the hour after changing to integer 
print(h)

Week Number %U

Based on Week number print Yes ( if even ) or print No ( if odd )
from datetime import date
dt = int(date.today().strftime('%U')) # integer output of string number 
if(dt % 2 == 0):
    print('Yes') 
else:
    print('No')

Handling Locale-Specific Date and Time Formats

The strftime() function can format dates and times according to the locale settings of your system. This is particularly useful for applications that need to display dates and times in a format appropriate to the user's locale.
from datetime import datetime
import locale

# Set locale to German (Germany)
locale.setlocale(locale.LC_TIME, 'de_DE.utf8')

now = datetime.now()
formatted_date = now.strftime('%A, %d. %B %Y')
print(formatted_date) # Output: 'Dienstag, 17. September 2019'
In this example, we set the locale to German and format the current date to display the day of the week, day, month, and year in German. Ensure that the desired locale is installed on your system; otherwise, you may encounter a locale.Error.

Formatting Time Zones and UTC Offsets

When working with time zones, it's often necessary to include the time zone name or UTC offset in your formatted date strings. The strftime() function provides directives for this purpose.
from datetime import datetime
import pytz

# Set timezone to US/Eastern
tz = pytz.timezone('US/Eastern')
now = datetime.now(tz)
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S %Z%z')
print(formatted_date) # Output: '2019-09-17 10:51:02 EDT-0400'
In this example, we use the pytz library to set the timezone to US/Eastern and format the current date and time to include the time zone abbreviation (%Z) and the UTC offset (%z).

Handling Week Numbers

The strftime() function can also format dates to include the week number of the year, which can be useful for applications that need to display or calculate information based on week numbers.
from datetime import datetime

now = datetime.now()
week_number = now.strftime('%U')
print('Week number:', week_number) # Output: 'Week number: 38'

In this example, %U is used to get the week number of the year, with Sunday as the first day of the week. Alternatively, %W can be used if Monday is considered the first day of the week.

Common Pitfalls and How to Avoid Them

When using strftime(), it's important to be aware of certain pitfalls to ensure your code behaves as expected.

  • Platform-Specific Behavior: The full set of format codes supported by strftime() can vary across platforms because Python calls the platform C library's strftime() function. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.
  • Zero-Padding in Format Codes: By default, certain format codes like %m and %d produce zero-padded results (e.g., 01 for January). If you prefer non-zero-padded results, you can remove the padding using platform-specific directives. For example, on Windows, you can use %-m and %-d to remove zero-padding. More details can be found on Enthought.
  • Locale Dependency: The output of locale-specific format codes (e.g., %c, %x, %X) depends on the current locale setting. Ensure that the appropriate locale is set in your environment to get the desired output.

All Date Objects strptime() string to Date and time object
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer