circuit

How to Store Date and Time in Python

Using the datetime Python library to store date and time efficiently


The datetime library allows us to store easily dates and times in our programs. It provides three main classes:

  • date, for storing only dates
  • time, for storing only the time of the day
  • datetime, for storing both date and time

In the following sections, we will see how to use these three classes.

Creating a new variable

Class Constructors

Each class has its own constructor. For the dateclass, it is

d = date(year, month, day)

Each value should be an integer, and the year can be any number between 1 and 9999.

For the timeclass, you can specify hours, minutes, seconds, microseconds:

t = time(hour, minute, second, microsecond)

Each variable must be in the following range:

  • 0 ≤ hour < 24
  • 0 ≤ minute < 60
  • 0 ≤ second < 60
  • 0 ≤ microsecond < 1000000

Finally, the constructor for datetimecontains fields for both date and time:

dt = datetime(year, month, day, hour, minute, second, microsecond)

Create from a String

datetimeobjects can also be created starting from a String, by using the following method (this is not available for time or date):

dt = datetime.strptime(date_string, format)

The format variable is a string that describes the format used by the date_string . For example:

dt = datetime.strptime("12:30 15/06/2021", "%H:%M %d/%m/%Y")

There are many symbols that can be used to specify the format of the string. The most important are:

  • %d for the zero-padded day of the month (01, 02, …, 31). You may also use %-d instead to avoid the leading zero (1, 2, …, 31)
  • %B for the full name of the month (January, February, …)
  • %m for the zero-padded number of the month (01, 02, …, 12). There is also %-m to avoid using the leading zero (1, 2, …, 12)
  • %Y for the year (1999, 2021, …)
  • %H for the hour of the day (24-hour) zero-padded (00, 01, …, 23) or %-H for removing the leading zero (0, 1,…, 23)
  • %I for the hour of the day on a 12-hour clock, zero-padded (01, 02, …, 12) or %-I for removing the leading zero (1, 2, …, 12). You should then use %p to indicate AM or PM
  • %M for the minutes, zero-padded (00, 01, …,59) or %-M for removing the leading zero (0, 1,…, 59)
  • %S for the seconds, zero-padded (00, 01, …, 59) or %-S for removing the leading zero (0, 1,…, 59)
  • %f for the microseconds, zero-padded(000000, 000001, …, 999999)

To see a full list, check here.

Modifying an object

It is possible to modify a single field of an object by using the replace method. This function will return a new object of the same type, where all the values are the same except for the specified ones. It can be used by all classes.

d = date(2021, 7, 20)
# d represents 20/7/2021
newDate = d.replace(day = 30)
# Now newDate represents 30/7/2021

Getting values from objects

The values of the day, month, year (for date ), and of hours, minutes, seconds, microseconds (for time ) can be accessed as read-only fields. The datetime objects have all the previously mentioned fields.

dt = datetime(2021, 7, 21, 14, 30, 0, 0)
hour = dt.hour # Get the hour stored in dt
day = dt.day # Get the day stored in dt
# etc

Get the data as a String

We can also get the value stored in a date , time or datetime object as a string by using their method strftime . You only need to pass the format which should be used to create the string, such as:

dt = datetime(2021, 7, 21, 14, 30, 0, 0)
print(dt.strftime("%H:%M %d/%m/%Y"))
# Will output:    14:30 21/07/2021

To check which symbols can be used in the format string, see here.

Get the day of the week

The function weekday() can be used with date or datetime objects to get the day of the week as an integer: Monday is 0, Sunday is 6.

d = date(2021, 7, 28)
week_day = d.weekday() # This will be 2 (Wednesday)

Arithmetic operations

With the Datetime library, it is also possible to perform arithmetic operations over dates and times. In order to do so there is another class, timedelta , that is used to store the time elapsed between two other dates (or times) in microseconds. The constructor is:

timedelta(_days=0_, _seconds=0_, _microseconds=0_, _milliseconds=0_, _minutes=0_, _hours=0_, _weeks=0_)

To get the total time stored in a timedeltaobject in seconds, you can use the timedelta.total_second() method.

elapsed = timedelta(hours = 1)
print(elapsed.total_seconds()) # This will print 3600

This class can be used to increase or reduce the value stored in a time(or date) object. In the following examples, we will see how to perform operations with datetime objects, but the same can be achieved with date or time .

We can:

  • Subtract two datetime between them to get a timedelta object
  • Add a timedelta to a datetime to get a new datetime
  • Subtract a timedelta from a datetime to get a new datetime

Other useful methods

There are many other methods that can be useful when dealing with dates. First of all, there is a built-in method to get the current date and time:

  • date.today() returns a date object with today’s date
  • datetime.now() returns an object with the current date and time

Converting objects

We can also convert a datetime to a date object or a time object by using the methods datetime.date() and datetime.time() .

dt = datetime(2021, 7, 21, 14, 30, 0, 0)
d = dt.date() # A date object representing 21/7/2021
t = dt.time() # A time object representing 14:30:00

Conclusion

Thank you for reading through to the end! I hope this article has helped you understanding how to use the datetime library. If you need more information, you can check the documentation for this library.




Continue Learning