You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here

Answer from Levon on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
Return a date corresponding to a date_string given in any valid ISO 8601 format, with the following exceptions: Reduced precision dates are not currently supported (YYYY-MM, YYYY). Extended date representations are not currently supported (±YYYYYY-MM-DD). Ordinal dates are not currently supported (YYYY-OOO). ... >>> import datetime as dt >>> dt.date.fromisoformat('2019-12-04') datetime.date(2019, 12, 4) >>> dt.date.fromisoformat('20191204') datetime.date(2019, 12, 4) >>> dt.date.fromisoformat('2021-W01-1') datetime.date(2021, 1, 4)
🌐
Programiz
programiz.com › python-programming › datetime › strftime
Python strftime() - datetime to string
We also recommend you to check Python strptime(). The strptime() method creates a datetime object from a string.
Top answer
1 of 15
806

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here

2 of 15
325

date and datetime objects (and time as well) support a mini-language to specify output, and there are two ways to access it:

  • direct method call: dt.strftime('format here')
  • format method (python 2.6+): '{:format here}'.format(dt)
  • f-strings (python 3.6+): f'{dt:format here}'

So your example could look like:

  • dt.strftime('The date is %b %d, %Y')
  • 'The date is {:%b %d, %Y}'.format(dt)
  • f'The date is {dt:%b %d, %Y}'

In all three cases the output is:

The date is Feb 23, 2012

For completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:

'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012

The time taken to learn the mini-language is worth it.


For reference, here are the codes used in the mini-language:

  • %a Weekday as locale’s abbreviated name.
  • %A Weekday as locale’s full name.
  • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
  • %d Day of the month as a zero-padded decimal number.
  • %b Month as locale’s abbreviated name.
  • %B Month as locale’s full name.
  • %m Month as a zero-padded decimal number. 01, ..., 12
  • %y Year without century as a zero-padded decimal number. 00, ..., 99
  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %H Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23
  • %I Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12
  • %p Locale’s equivalent of either AM or PM.
  • %M Minute as a zero-padded decimal number. 00, ..., 59
  • %S Second as a zero-padded decimal number. 00, ..., 59
  • %f Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999
  • %z UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030
  • %Z Time zone name (empty if naive), UTC, EST, CST
  • %j Day of the year as a zero-padded decimal number. 001, ..., 366
  • %U Week number of the year (Sunday is the first) as a zero padded decimal number.
  • %W Week number of the year (Monday is first) as a decimal number.
  • %c Locale’s appropriate date and time representation.
  • %x Locale’s appropriate date representation.
  • %X Locale’s appropriate time representation.
  • %% A literal '%' character.
🌐
Educative
educative.io › answers › how-to-convert-a-string-to-a-date-in-python
How to convert a string to a date in Python
The syntax for the method used to convert string to datetime object is strptime(x,y) where:
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-to-datetime-strptime
How To Convert a String to a datetime Object in Python | DigitalOcean
December 13, 2024 - In this article, you’ll use strptime() to convert strings into datetime and struct_time() objects. Deploy your Python applications from GitHub using DigitalOcean App Platform.
🌐
Python documentation
docs.python.org › 3 › whatsnew › 3.14.html
What’s new in Python 3.14
4 weeks ago - Add the strptime() method to the datetime.date and datetime.time classes.
Find elsewhere
🌐
CoenRaets
jsonviewer.ai › python-string-to-datetime
Best Ways to Convert Python String to DateTime[with Code] - JSON Viewer
July 29, 2023 - Each format has its representation for year, month, and day. Understanding these formats is crucial before converting strings to DateTime objects. Python’s datetime.strptime() method allows you to convert a date string into a DateTime object based on a specific format.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-convert-a-string-to-a-datetime-object-in-python
How to Convert a String to a DateTime Object in Python
December 17, 2024 - The solution to this problem is to parse (or convert) the string object into a datetime object so Python can recognized it as a date.
🌐
Code Beautify
codebeautify.org › blog › how-to-convert-string-to-date-using-to-python
How to Convert String to Date Using to Python
February 22, 2024 - We import the datetime module. Define the string representing the date (date_string) and the format (date_format) it is in. Use strptime() function to convert the string to a datetime object.
🌐
PYnative
pynative.com › home › python › python datetime › python string to datetime using strptime()
Python String to DateTime using Strptime() [5 Ways] – PYnative
December 5, 2021 - import time # time hours-minutes-seconds format time_string = "09-15-09" format_codes = "%H-%M-%S" time_obj = time.strptime(time_string, format_codes) print("Time Object", time_obj) print(type(time_obj))Code language: Python (python) Run ... Time Object time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=9, tm_min=15, tm_sec=9, tm_wday=0, tm_yday=1, tm_isdst=-1) <class 'time.struct_time'> This method basically converts the string into a datetime object according to a format.
🌐
Accuweb
accuweb.cloud › home › how to convert a string to a datetime or time object in python
How To Convert a String to a datetime or time Object in Python - AccuWeb Cloud
December 1, 2023 - You can convert a string to a datetime or time object in Python using the datetime module, which provides various functions and classes for working with date and time values.
🌐
IONOS
ionos.com › digital guide › websites › web development › convert strings to datetime in python
How to convert a string to datetime in Python - IONOS
December 17, 2024 - The strptime() (string parse time) method from the datetime library is used to convert a string into a Python datetime object.
🌐
PythonHow
pythonhow.com › how › convert-a-string-into-datetime-format
Here is how to convert a string into datetime format in Python
from datetime import datetime # The string to be converted date_string = "2022-12-15 12:30:00" # The format in which the string represents a date and time date_format = "%Y-%m-%d %H:%M:%S" # Convert the string to a datetime object date_time = datetime.strptime(date_string, date_format) # Print ...
🌐
Home Assistant
community.home-assistant.io › t › converting-a-string-to-datetime-in-python › 141614
Converting a string to datetime in python - Home Assistant Community
July 24, 2019 - as imports are not allowed - ho do i do this? need to substract a datetime from another represented by string
🌐
Databricks Community
community.databricks.com › t5 › data-engineering › how-to-convert-string-to-datetime-with-correct-timezone › td-p › 10741
How to convert string to datetime with correct tim... - Databricks Community - 10741
December 20, 2024 - Secondly, from what I can tell, using the TO_TIMESTAMP function will apply the timezone for your session (which might not be the timezone you want). I didn't realise this could be solved pretty easily by simply pasting your timezone to the end of the date string, like this;
🌐
FastAPI
fastapi.tiangolo.com › python-types
Python Types Intro - FastAPI
Pydantic is a Python library to perform data validation. You declare the "shape" of the data as classes with attributes. And each attribute has a type. Then you create an instance of that class with some values and it will validate the values, convert them to the appropriate type (if that's the case) and give you an object with all the data. And you get all the editor support with that resulting object. ... from datetime import datetime from pydantic import BaseModel class User(BaseModel): id: int name: str = "John Doe" signup_ts: datetime | None = None friends: list[int] = [] external_data = { "id": "123", "signup_ts": "2017-06-01 12:22", "friends": [1, "2", b"3"], } user = User(**external_data) print(user) # > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] print(user.id) # > 123
🌐
Mimo
mimo.org › glossary › python › datetime
Mimo: The coding platform you need to learn Web Development, Python, and more.
In this example, the string 2024-09-19 15:45:30 is converted into a datetime object using the format "%Y-%m-%d %H:%M:%S". You can adjust the format string to match different date and time formats.
🌐
AskPython
askpython.com › home › convert string to datetime using python strptime()
Convert string to datetime using Python strptime() - AskPython
May 8, 2020 - The Python strptime() method is available in both datetime and time modules. It is used to parse a given string into datetime or time object according to the specified format.