The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.
What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().
The How: what do you want to do with that?
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).
One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist : print str(date)Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)
Practical case, using your code
import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] # print the date object, not the container ;-) 2008-11-22 # It's better to always use str() because : print "This is a new day : ", mylist[0] # will work >>> This is a new day : 2008-11-22 print "This is a new day : " + mylist[0] # will crash >>> cannot concatenate 'str' and 'datetime.date' objects print "This is a new day : " + str(mylist[0]) >>> This is a new day : 2008-11-22Advanced date formatting
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.
strftime() expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y') >>> 'We are the 22, Nov 2008'All the letter after a "%" represent a format for something:
- %d is the day number (2 digits, prefixed with leading zero's if necessary)
- %m is the month number (2 digits, prefixed with leading zero's if necessary)
- %b is the month abbreviation (3 letters)
- %B is the month name in full (letters)
- %y is the year number abbreviated (last 2 digits)
- %Y is the year number full (4 digits)
etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today) >>> 'We are the 22, Nov 2008'The advantage of this form is that you can also convert other objects at the same time.
With the introduction of
Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
Localization
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values.
Required library
import datetimeThe datetime.time method
Time values can be represented using the time class. The attributes for the time class include the hour, minute, second, and microsecond.
Syntax of datetime.time
time(hour, minute, second, microsecond)Example 1:
Python3
import datetime
tm = datetime.time(2, 25, 50, 13)
print(tm)
Output
02:25:50.000013Example 2:
There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanoseconds, range is between 0 to 999999. If the range exceeds, the compiler shows a ValueError. The instance of time class consists of three instance attributes namely hour, minute, second, and microsecond. These are used to get specific information about the time.
Python3
import datetime
tm = datetime.time(1, 50, 20, 133257)
print('Time tm is ',
tm.hour, ' hours ',
tm.minute, ' minutes ',
tm.second, ' seconds and ',
tm.microsecond, ' microseconds')
Output
Time tm is 1 hours 50 minutes 20 seconds and 133257 microseconds
The datetime.date method
The values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day.
Syntax of datetime.date
date(yyyy, mm, dd)Example 1:
Python3
import datetime
date = datetime.date(2018, 5, 12)
print('Date date is ', date.day,
' day of ', date.month,
' of the year ', date.year)
Output
Date date is 12 day of 5 of the year 2018Example 2:
To get today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used.
Python3
import datetime
tday = datetime.date.today()
daytoday = tday.ctime()
print("The date today is ", tday)
print("The date info. is ", daytoday)
Output
The date today is 2020-01-30 The date info. is Thu Jan 30 00:00:00 2020Convert string to date using DateTime
Conversion from string to date is many times needed while working with imported data sets from a CSV or when we take inputs from website forms. To do this, Python provides a method called strptime().
Syntax: datetime.strptime(string, format)
Parameters:
- string – The input string.
- format – This is of string type. i.e. the directives can be embedded in the format string.
Example:
Python3
from datetime import datetime
print(datetime.strptime('5/5/2019',
'%d/%m/%Y'))
Output
2019-05-05 00:00:00Convert dates to strings using DateTime
Date and time are different from strings and thus many times it is important to convert the DateTime to string. For this, we use strftime() method.
Syntax of datetime.strftime
Syntax: datetime.strftime(format, t)
Parameters:
- format – This is of string type. i.e. the directives can be embedded in the format string.
- t – the time to be formatted.
Example 1:
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%b %d %Y %H:%M:%S"))
Output
May 12 2018 02:25:50Example 2:
The same example can also be written in a different place by setting up the print() method.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%H:%M:%S %b %d %Y"))
Output
02:25:50 May 12 2018%H, %M and %S displays the hour, minutes and seconds respectively. %b, %d and %Y displays 3 characters of the month, day and year respectively. Other than the above example the frequently used character code List along with its functionality are:
Frequently used character code in DateTime
- %a: Displays three characters of the weekday, e.g. Wed.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%a"))
Output
Sat- %A: Displays name of the weekday, e.g. Wednesday.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%A"))
Output
Saturday- %B: Displays the month, e.g. May.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%B"))
Output
May- %w: Displays the weekday as a number, from 0 to 6, with Sunday being 0.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%w"))
Output
6- %m: Displays month as a number, from 01 to 12.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%m"))
Output
5- %p: Define AM/PM for time.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%p"))
Output
PM- %y: Displays year in two-digit format, i.e “20” in place of “2020”.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("% y"))
Output
18- %f: Displays microsecond from 000000 to 999999.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("% f"))
Output
000013- %j: Displays number of the day in the year, from 001 to 366.
Python3
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%f"))
Output
132