Time and DateTime in Python
LeonDoesCode (275)

Why?

I have doubt that most of you have used the time and datetime modules in Python. However, I also would also say that most of you don't know its full capabilities either. If you have used the time module, then chances are that it was to get a time, date or maybe even test the time it task your functions to execute.

Modules

As mentioned before, we will be covering the time and datetime modules. However, to go with these, there is one function from the calendar module we will be using. They are all in the standard library. These modules allow us to get times and dates based on epoch, utc and local times.

  • Epoch is the time elapsed since 1st January 1970 00:00:00.
  • UTC (Coordinated Universal Time) is within ~1 second of mean solar time. Your country may use GMT (Greenwich Mean Time) instead.
  • Local time is the time reckoned for your region.

When we get these times, they will be in one of these data types.

  • struct_time which is a tuple containing the data for the time.
  • str which will be the time and possibly date.
  • float which will most likely be a time in seconds.
  • int whcih will most likely be a time in nano seconds.

Note: What you see below is going to be a lot of code, I mean, a lot. But it comes with explanations like always.

Time

To get started with time, we need to do some importing:

import time
import calendar

Now we can begin!

Some of the commonly used functions consist of:

# This will make the program sleep for the specified amount of seconds
time.sleep(1)

# Return time since epoch
print(time.time())
# Return the same value but in nano seconds
print(time.time_ns())

You may have used them to add a dramatic flair to your game or to get the weather at a specific time. But there are so many other things that are in the time module.

Now, lets move onto some of the more advanced things that we talked about above:

# From seconds since epoch to utc time
epochtoutc = time.gmtime()
print(epochtoutc)
# From seconds since epoch to local time
epochtolocal = time.localtime()
print(epochtolocal)

print()

# From utc time to seconds since epoch
utctoepoch = calendar.timegm(epochtoutc)
print(utctoepoch)
# From utc time to seconds since epoch
localtoepoch = time.mktime(epochtolocal)
print(localtoepoch)

The first two functions will get the utc and local time from the epoch, whereas, the second two functions get the epoch from the utc and local times.

# Returns a string from struct_time, which is created by gmtime() and localtime()
print(time.asctime(epochtoutc))
print(time.asctime(epochtolocal))

print()

# Similar function, but can have a format, see https://docs.python.org/3/library/time.html#time.strftime
print(time.strftime("%A %B %d %H:%M:%S %Y", epochtoutc))

In this case, we are making strings out of the times we got from before. This makes it much easier if we just want to display the date and not get anything specific from it.

# Returns the value of a monothic clock (doesn't go backwards)
print(time.monotonic())
# Return that same value but as nano seconds
print(time.monotonic_ns())

This will get the value of a monothic click. These asre useful as they don't go back or leap forward. They are one steady clock which goes up by one each time.

# Returns the value of a high resolution clock
print(time.perf_counter())
# Return that same value but as nano seconds
print(time.perf_counter_ns())

This is another clock, but unlike the others, it has a high resolution. This is great to use if you are measuring small changes in time, or need a a highly accurate value for your program.

# Returns the sum of system and cpu time in this process
print(time.process_time())
# Return that same value but as nano seconds
print(time.process_time_ns())

This returns the runtime of the program. It does this based on the system and CPU times. This can become very useful to check if some time has ellapsed in your program.

Notice that the functions which return float values (which are most likely seconds), also have another function with _ns at the end. This will return that functions output but as an int, which will be that value but in nano seconds.

DateTime

Fistly, we need to import our modules:

import datetime
import time

Let's cover some of the basic functionality that comes with the datetime module.

# Returns a datetime class which has its values equal to the current time
print(datetime.datetime.today())
print(datetime.datetime.now())
# Returns a datetime class which has its values equal to the timestamp (time.time())
print(datetime.datetime.fromtimestamp(time.time()))

These will return datetime classes which equal the current date or the timestamps date. Here the timestamp is time.time(), but this could be a timestamp that you saved earlier.

# Creates a date class with year month and day (required)
date = datetime.date(2019, 10, 31)
print(date)

# Creates a time class which can have hour minute second microsecond (not reqired)
time = datetime.time(12, 6, 30, 5)
print(time)

# Creates a datetime class which is a combination of both date and time
dt = datetime.datetime(2019, 10, 31, 21, 6, 30, 5)
print(dt)

These are simple classes which allow you to easier represent the time, date or both at the same time. For date and datetime, the year, month and day should be integers and are required. time takes in hour, minute, second and microsecond as integers, but they will default to 0 if not given.

# Creates a timedelta class which takes in days, seconds, microseconds, milliseconds, minutes, hours and/or weeks for use in calculations
delta = datetime.timedelta(days=1, seconds=2, microseconds=3, milliseconds=4, minutes=5, hours=6, weeks=1)
print(delta)

print()

# You can use operators like normal on two different timedelta classes, the resulting class will be a timedelta of the result of that the operation on the two classes
start = datetime.timedelta(seconds=-1)
end = datetime.timedelta(seconds=1)
# (end - start) = 2 seconds * 2 = 4 seconds
res = (end - start) * 2
print(res)

timedeltas can prove very useful when comparing times. Having the ability to compare them using our normal operators (+, -, *, /...) makes it much more convenient as well.

# Creates an ordinal from a date class
ordinal = datetime.date(year=2, month=5, day=1).toordinal()
print(ordinal)
# Then this creates a date class from an ordanal
notordinal = datetime.date.fromordinal(ordinal)
print(notordinal)

print()

# Similarly, this creates an iso from a datetime class
iso = datetime.datetime(year=2, month=5, day=1, hour=5, minute=2).isoformat()
print(iso)
# Then this creates a datetime class from an iso
notiso = datetime.datetime.fromisoformat(iso)
print(notiso)

This allows us to convert the datetime into something that might be useful in other programs. It is also a smaller value to save and/or use.

# You can get the week day (0-6) from a datetime class
week = notiso.weekday()
print(week)

print()

# You can get data from the datetime class using a format
print(notiso.strftime("%H:%M:%S"))

Again, this might come in useful uif you only need a bit of data from the datetime, or want to get it in a specific style.

Note: These functions, for the most part, also apply to the time and date classes.

Conclusion

There are a lot more to these classes then most people thing, even more than what I've shown here. It's always best to play around with the docs to see what you can find use in.

P.S
This tutorial was suggested by @TristanMisja .
If you have any suggestions for tutorials, leave them in the comments and I'll be sure to have a look. If you like one in the comments, then give it an up vote to show that you want to see it. It makes my life so much more easier. Thanks in advance!

You are viewing a single comment. View All