Skip to main content
Published on

Date and Time in Python

Share:

Introduction

Handling dates and times is fundamental in many programming projects. Whether it is to record when an event occurred, schedule future tasks, or calculate the difference between two dates, Python offers robust tools for this purpose.

Working with Date and Time in Python

In Python, there are several modules for dealing with dates and times. The time module is one of the most common and provides functions for working with time in ticks, as well as converting those ticks into more readable formats.

Basic Functions

Here are some of the fundamental functions provided by the time module:

# from calendar import *
from time import *

# print(calendar(2021))
# print(month(2021, 8))
print(time()) # 1628197388.7380881
print(localtime(time())) # time.struct_time(tm_year=2021, tm_mon=8, tm_mday=5, tm_hour=22, tm_min=3, tm_sec=8, tm_wday=3, tm_yday=217, tm_isdst=1)
print(asctime(localtime(time()))) # Thu Aug 5 22:03:08 2021

Explaining the Functions

  • calendar(year): Returns a complete calendar for the specified year.
  • month(year, month): Displays the calendar for a specific month of the given year.
  • time(): Returns the current time in ticks, which are fractions of a second since the "Epoch", 00:00:00 on January 1, 1970.
  • localtime(time()): Converts ticks into a local time structure.
  • asctime(localtime(time())): Converts the time structure into a human-readable string.

Other Useful Functions

There are other useful functions worth exploring, such as date formatting with strftime and obtaining the difference between two dates with difftime.

Conclusion

The time module is just the tip of the iceberg when it comes to handling dates and times in Python. There are other modules, such as datetime and dateutil, that provide even more functionality. Mastering these tools can be very beneficial, especially if you are working on applications that require intensive date and time manipulation.

Happy coding!