PYTHON LESSON 2: Date & Time
The Datetime Library;
A lot of times you want to keep track of when something happened. We can do so in Python using .
Here we’ll use datetime to print the date and time in a nice format.
Getting the Current Date and Time
We can use a function called datetime.now() to retrieve the current date and time.
from datetime import datetime \n print datetime.now() |
|---|
The first line imports the datetime library so that we can use it.
The second line will print out the current date and time.
Extracting Information;
Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don’t want the entire date and time?
from datetime import datetime \n now = datetime.now() \n \n current_year = now.year \n current_month = now.month \n current_day = now.day |
|---|
You already have the first two lines.
In the third line, we take the year (and only the year) from the variable now and store it in current_year.
In the fourth and fifth lines, we store the month and day from now.
Hot Date;
What if we want to print today’s date in the following format? mm/dd/yyyy. Let’s use string substitution again!
from datetime import datetime \n now = datetime.now() \n \n print '%02d-%02d-%04d' % (now.month, now.day, now.year) \n # will print the current date as mm-dd-yyyy |
|---|
Remember that the standalone % operator after the string will fill the %02d and %04d placeholders in the string on the left with the numbers and strings in the parentheses on the right.
%02d pads the month and day numbers with zeros to two places, and %04d pads the year to four places. This is one way dates are commonly displayed.
Pretty Time;
Let’s do the same for the hour, minute, and second.
from datetime import datetime \n now = datetime.now() \n \n print now.hour \n print now.minute \n print now.second |
|---|
In the above example, we just printed the current hour, then the current minute, then the current second.
We can again use the variable now to print the time.
Grand Finale;
We’ve managed to print the date and time separately in a very pretty fashion. Let’s combine the two!
from datetime import datetime \n now = datetime.now() \n print '%02d/%02d/%04d' % (now.month, now.day, now.year) \n print '%02d:%02d:%02d' % (now.hour, now.minute, now.second) |
|---|
The example above will print out the date, then on a separate line it will print the time.
Let’s print them all on the same line in a single print statement!
print '%02d/%02d/%04d %02d:%02d:%02d' % (now.month, now.day, now.year, now.hour, now.minute, now.second) |
|---|
Try it out in your python program!