How to use Date and Time in Python

This post will show some examples using Pythons datetime and time modules.

In a previous post, basic date and time types in Python, I wrote that the datetime and time objects all support a strftime(format) method to create a string representing the time under the control of an explicit format string.

Date and Time Example

Let’s see what we can do with the datetime and time modules in Python

import time
import datetime

print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " ,
print "Or like this: " ,"%y-%m-%d-%H-%M")

print "Current year: ","%Y")
print "Month of year: ","%B")
print "Week number of the year: ","%W")
print "Weekday of the week: ","%w")
print "Day of year: ","%j")
print "Day of the month : ","%d")
print "Day of week: ","%A")


That will print out something like this:

Time in seconds since the epoch: 	1349271346.46
Current date and time:  		2012-10-03 15:35:46.461491
Or like this: 				12-10-03-15-35
Current year:  				2012
Month of year:  			October
Week number of the year:  		40
Weekday of the week:  			3
Day of year:  				277
Day of the month :  			03
Day of week:  				Wednesday

Getting the weekday of a certain date (your pet’s birthday).

import datetime

mydate =,3, 13)  #year, month, day

Leave a Reply

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