Date and Time in Python
Tags: beginners
Published: 2024-02-20 03:53:09

When working with real-world data you often have to deal with dates and times. Date and times can be tricky to work with, because people format and present them in different ways. Consider, for example, a date written as "02-03-1998". Does this represent 2nd March 1998, or 3rd February 1998? In Australia it would be the former, but in the US it would be the latter.

Python has a datetime library that defines datetime , date, and time types. These provide a uniform and comprehensive way to handle dates and times. The datetime type is the most flexible and thus the most commonly used. There is also a timedelta type, which is used to work with durations (i.e., time intervals).

To use these you need to import them:

`from datetime import datetime, date, time, timedelta`

You don't need to import them all - just the ones you will be using.

Usually your goal will be to convert a string or integer representation of a date or time into a datetime object, apply whatever processing you need to the object, and then use a formatting function to convert it back to a traditional format.

**Creating a datetime object**
There are several ways to create a datetime object.

You can directly construct it by providing the year, month, and day, and, optionally, the time and timezone.

`from datetime import datetime
dt = datetime(
    year = 1968, month = 6, day = 24,
    hour = 5, minute = 30, second = 0
)
print(dt)`

You can also construct it from a string. In this case you need to tell Python what format the string uses:

`from datetime import datetime
dt = datetime.strptime('24-06-1968, 05:30:00', '%d-%m-%Y, %H:%M:%S')
print(dt)`

The trickiest part about this is remembering what the formatting codes are. You'll probably find yourself looking them up quite often. Here are the main ones:

%Y Four-digit year (1968)
%y Two-digit year (68)

%B Full month name (June)
%b Abbreviated month name (Jun)
%m Two-digit month number (01-12)

%A Full day name (Monday)
%a Abbreviated day name (Mon)
%d Two-digit day number (01-31)

%H Two-digit hour (00-23)
%I Two-digit hour (00-12)

%M Two-digit minute (00-59)
%S Two-digit second (00-59)

%p AM/PM

If you want a datetime object that represents the current date and time you can use the now method:

`from datetime import datetime
dt = datetime.now()
print(dt)`

**Unix timestamp**
You can also construct a datetime object from a Unix timestamp. This is one of the most common representations of time.  It represents the time as a numerical value - the number of seconds since the Unix epoch, which was at 00:00:00 on Thursday, 1 January 1970 UTC. You can get the current Unix timestamp using the time.time function.

`from time import time
print(time())`

To create a datetime object from a Unix timestamp you can use use datetime.fromtimestamp().

`from datetime import datetime
x = datetime.fromtimestamp(1565315907)
print(x)`

**Extracting the components of a datetime object**
Once you have a datetime object you can extract its individual components:

`from datetime import datetime
dt = datetime(
    year = 1968, month = 6, day = 24,
    hour = 5, minute = 30, second = 0
)
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)`

You can also extract a date object or a time object from a datetime object:

`from datetime import datetime
dt = datetime(
    year = 1968, month = 6, day = 24,
    hour = 5, minute = 30, second = 0
)
print(dt.date())
print(dt.time())`

**Formatting a datetime object as a string**
A very common thing to do is to present a datetime object in a certain format. You can use the strftime method, to do this. You need to specify the format you would like, using the same formatting codes as listed above.

`from datetime import datetime
dt = datetime(
    year = 1968, month = 6, day = 24,
    hour = 5, minute = 30, second = 0
)
print(dt.strftime('%d %B %Y, at %I:%M %p'))`

**Operating on datetime objects**
One of the most useful features of datetime objects is that you can very easily calculate new dates and times. The datetime module is so nicely designed that the following examples should be self-explanatory:

First example:

`from datetime import datetime, timedelta
now = datetime.now()
print(now + timedelta(hours=1))
print(now + timedelta(days=1))
print(now - timedelta(weeks=2))
print(now + timedelta(weeks=4, days=3, hours=2, seconds=45))`

Second example:

`from datetime import datetime, timedelta
new_years_eve = datetime(year=2024, month=12, day=31)
now = datetime.now()
time_remaining = new_years_eve - now
print(time_remaining)`