October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Convert Datetime to String in Python and Django

Use Python’s strftime() or isoformat() for datetime strings, and Django’s date or time filter for template output. The format codes and timezone behavior differ.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s strftime() or isoformat() to turn a datetime into a string. In a Django template, use the date filter with Django’s format codes. The syntax differs: Python writes minutes as %M, while Django writes them as i. Choose the method and timezone behavior according to whether the output is for display or a stable machine-readable value.

Format a datetime in Python

Call strftime() with Python’s percent-prefixed format directives when you need to control the output layout:

from datetime import datetime

dt = datetime(2024, 3, 5, 14, 9, 7)
text = dt.strftime("%Y-%m-%d %H:%M:%S")
# "2024-03-05 14:09:07"

Common directives are %Y for a four-digit year, %m for a zero-padded month, %d for a zero-padded day, %H for a 24-hour hour, %M for minutes, and %S for seconds. The supported set can vary by platform because Python’s strftime() relies on the platform C library. See the Python datetime documentation.

Use ISO-style output when appropriate

For an ISO-style representation, call isoformat():

text = dt.isoformat()

For a datetime, str(dt) is equivalent to dt.isoformat(' '), using a space between the date and time. If another system depends on the exact representation, choose the method explicitly rather than relying on an implicit string conversion. An aware datetime’s ISO output can include its UTC offset; verify that the receiving system expects that representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Formatting is not parsing

strftime() formats a date or time object as text. To parse text back into a datetime, use datetime.strptime(date_string, format) with a matching format string. The two operations go in opposite directions.

Format a datetime in a Django template

Use Django’s built-in date filter for a date or datetime:

{{ value|date:"Y-m-d H:i:s" }}

Django’s format codes are not Python’s strftime() directives. In this example, Y is the four-digit year, m the zero-padded month, d the zero-padded day, H the 24-hour hour, i the minute, and s the second. The equivalent-looking Python format would use percent-prefixed codes, including %M for minutes. Consult the Django template filter reference for the available codes and predefined formats.

Use the time filter for time-only output

For a time-only value, use Django’s time filter. It accepts time-related format parameters and, for an aware datetime, certain timezone-related codes. For a complete date and time, date is usually the clearer choice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the right format for display or data exchange

  • Python application code: use strftime() when you need a specific layout, or isoformat() for an ISO-style representation.
  • Django template display: use date for dates and datetimes, or time for time-only output.
  • Machine-readable output: choose an explicit representation and establish whether a timezone offset must be included. Avoid formats whose output changes with the active locale or project configuration.
  • Human-facing output: Django’s predefined formats and localization can adapt to the active locale, which may be useful for readers but makes the rendered string less fixed.

Django supports locale-aware formats and custom format definitions, so a rendered value may depend on the active locale and configuration. See Django’s format localization documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Account for timezone awareness in Django

When Django timezone support is enabled, aware datetimes are converted to the current timezone when rendered in templates. Naive datetimes are not automatically converted: their intended timezone may be ambiguous. The Django 5.2 timezone documentation explains, “Django doesn’t convert naive datetime objects, because they could be ambiguous, and because your code should never produce naive datetimes when time zone support is enabled.” Read the Django timezone documentation.

For a display intended for a person, decide which current timezone should apply. For an API or other machine consumer, consider whether rendering in the current display timezone is appropriate; the output’s timezone and offset semantics should be intentional rather than accidental.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.