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 OverflowVideos
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
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:
%aWeekday as localeโs abbreviated name.%AWeekday as localeโs full name.%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.%dDay of the month as a zero-padded decimal number.%bMonth as localeโs abbreviated name.%BMonth as localeโs full name.%mMonth as a zero-padded decimal number. 01, ..., 12%yYear without century as a zero-padded decimal number. 00, ..., 99%YYear with century as a decimal number. 1970, 1988, 2001, 2013%HHour (24-hour clock) as a zero-padded decimal number. 00, ..., 23%IHour (12-hour clock) as a zero-padded decimal number. 01, ..., 12%pLocaleโs equivalent of either AM or PM.%MMinute as a zero-padded decimal number. 00, ..., 59%SSecond as a zero-padded decimal number. 00, ..., 59%fMicrosecond as a decimal number, zero-padded on the left. 000000, ..., 999999%zUTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030%ZTime zone name (empty if naive), UTC, EST, CST%jDay of the year as a zero-padded decimal number. 001, ..., 366%UWeek number of the year (Sunday is the first) as a zero padded decimal number.%WWeek number of the year (Monday is first) as a decimal number.%cLocaleโs appropriate date and time representation.%xLocaleโs appropriate date representation.%XLocaleโs appropriate time representation.%%A literal '%' character.
The datetime class has a method strftime. The Python docs documents the different formats it accepts: strftime() and strptime() Behavior
For this specific example, it would look something like:
my_datetime.strftime("%B %d, %Y")
Here is how you can accomplish the same using python's general formatting function...
>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())
The formatting characters used here are the same as those used by strftime. Don't miss the leading : in the format specifier.
Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated...
>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())
Compare the above with the following strftime() alternative...
>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))
Moreover, the following is not going to work...
>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string
And so on...
datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
To obtain a date object using an existing datetime object, convert it using .date():
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
Links:
strptimedocs: Python 2, Python 3strptime/strftimeformat string docs: Python 2, Python 3strftime.org format string cheatsheet
Notes:
strptime= "string parse time"strftime= "string format time"
Use the third-party dateutil library:
from dateutil import parser
parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0)
It can handle most date formats and is more convenient than strptime since it usually guesses the correct format. It is also very useful for writing tests, where readability is more important than performance.
Install it with:
pip install python-dateutil
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07