19. Accessing date and time, and timing code

Accessing date and time

It may sometimes be useful to access the current date and/or time. As an example, when writing code it may be useful to access the time at particular stages to monitor how long different parts of code are taking.

To access date and time we will use the datetime module (which is held in a package that is also, a little confusingly called datetime!):

from datetime import datetime

To access the current date and time we can use the now method:

print (datetime.now())


2018-03-28 08:54:13.623198

You might not have expected to get the time to the nearest microsecond! But that may be useful at times when timing short bits of code (which may have to run many times).

But we can access the date and time in different ways:

current_datetime = datetime.now()

print ('Date:', current_datetime.date()) # note the () after date
print ('Year:', current_datetime.year)
print ('Month:', current_datetime.month)
print ('Day:', current_datetime.day)
print ('Time:', current_datetime.time()) # note the () after time
print ('Hour:', current_datetime.hour)
print ('Minute:', current_datetime.minute)
print ('Second:', current_datetime.second)


Date: 2018-03-28
Year: 2018
Month: 3
Day: 28
Time: 08:54:13.636654
Hour: 8
Minute: 54
Second: 13

Having microseconds in the time may look a little clumsy. So let’s format the date and using the strftime method.

now = datetime.now()
print (now.strftime('%Y-%m-%d'))
print (now.strftime('%H:%M:%S'))



Timing code

We can use datetime to record the time before and after some code to calculate the time taken, but it is a little simpler to use the time module which keeps all time in seconds (from January 1st 1970) and gives even more accuracy to the time:

import time

time_start = time.time()

for i in range(100000):
    x = i ** 2

time_end = time.time()
time_taken = time_end - time_start

print ('Time taken:', time_taken)


Time taken: 0.03149104118347168

One thought on “19. Accessing date and time, and timing code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s