A date with Python's datetime module
Tags: python, tutorial, beginners, programming
Published: 2021-08-23 17:54:46


In this post, we are going to look at the **datetime** module in python. We will look at its functionality, uses and pros and cons.

##Definition of the Datetime Module
The datetime module in python gives us the ability to manipulate dates and times. Many applications require you to work with date and time. Familiarity with this module will enable you to work with different date and time formats in python.

You can categorize a datetime object as either **_aware_** or **_naive_**. This will depend on whether the object includes timezone information or not.

###Aware object
An Aware object can identify themselves relative to other time objects with the help of some parameters such as timezone and daylight saving information.

###Naive object
Naive objects don't contain enough information to identify themselves with other date or time objects.

The datetime objects have an optional timezone information attribute called **_tzinfo_**.  I will explain it in more depth later. This tzinfo lets us handle offset from UTC, timezone name and whether or not daylight saving time is in effect.

Enough talk, let us dive into Code.
First, we import the module.

`import datetime`

##datetime.date
**datetime.date** uses the [Georgian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) by default. The attribute of this class are:
* Year
* month
* and day

##datetime.time
**datetime.time** assumes standard everyday time conditions by default. That is: **24*60*60** seconds.
The attribute it contains are:
* hour
* minute
* second
* microsecond
* tzinfo

##datetime.datetime
This is a union of the datetime.date method and datetime.time method. It contains the following attributes:
* year
* month
* day
* hour
* minute
* second
* microsecond
* tzinfo

##datetime.timedelta
The term _delta_ in mathematics and computer science generally means _difference_. The timedelta class enables us to calculate the difference between date, time and datetime objects. You will use it a lot.

##Datetime.tzinfo
_Datetime.tzinfo_ is an abstract base class for timezone information. We use it to gain more control over timezones.

##Datetime.timezone
This redundant looking class implements the tzinfo abstract base class as a fixed offset from the UTC. It is mainly used with tzinfo because it maps the timezone to the UTC difference.

##Get current date and time with different time zones
If you are following along, note that the result will be different for you. Your output will depend on your own time.

```
datetime_object = datetime.datetime.now()
print(datetime_object)
# 2021-08-23 06:59:22.588129
#year-month-day hour:minute:second.microsecond

print(‘Year: ‘, datetime_object.year)
# Year: 2021

print(‘Month: ‘, datetime_object.month)
# Month: 8

print(‘Day: ‘, datetime_object.day)
# Day: 23

print(‘Hour: ‘, datetime_object.hour)
# Hour: 6

print(‘minute: ‘, datetime_object.minute)
# Minute: 59

print(‘Second: ‘, datetime_object.second)
# Seconds: 22

print(‘TimeZone info: ‘, datetime_object.tzinfo)
# TimeZone info: None
```

note that the timezone info is none, this is because we didnt make our datetime timezone info aware.
Lets fix this:

```
datetime_object.replace(tzinfo=datetime.timezone.utc)
# datetime.datetime(2021, 8, 23, 6, 59, 22, 588129, tzinfo=datetime.timezone.utc)
#its aware

print(‘Year: ‘, datetime_object.year)
# Year: 2021

print(‘Month: ‘, datetime_object.month)
# Month: 8

print(‘Day: ‘, datetime_object.day)
# Day: 23

print(‘Hour: ‘, datetime_object.hour)
# Hour: 6

print(‘minute: ‘, datetime_object.minute)
# Minute: 59

print(‘Second: ‘, datetime_object.second)
# Seconds: 22

print(‘TimeZone info: ‘, datetime_object.tzinfo)
# TimeZone info: UTC
```

Now we can see that the timezone has changed to UTC. We can make our datetime object more readable by using the isoformat method.

```
print(datetime_object.isoformat())
# 2021-08-23T06:59:22.588129
```

##pytz
we can use the pytz module if we want to use different timezones other than UTC. Take a look:

```
import pytz

print(pytz.all_timezones_set) # displays all timezones

new_timezone = pytz.timezone(‘Africa/Lagos’)
datetime_object = datetime.datetime.now(tz=new_timezone)
# make lagos my timezone and set it to my datetime object

print(‘Year: ‘, datetime_object.year)
# Year: 2021

print(‘Month: ‘, datetime_object.month)
# Month: 8

print(‘Day: ‘, datetime_object.day)
# Day: 23

print(‘Hour: ‘, datetime_object.hour)
# Hour: 6

print(‘minute: ‘, datetime_object.minute)
# Minute: 59

print(‘Second: ‘, datetime_object.second)
# Seconds: 22

print(‘TimeZone info: ‘, datetime_object.tzinfo)
# TimeZone info: Africa/Lagos

print(datetime_object.isoformat())
# 2021-08-23T15:49:07.495676+01:00
```

Getting only the current date

```
day = datetime.date.today()
print(day)
# 2021-08-23
```

##Getting a date from a timestamp

A timestamp is a Unix standard that defines the number of seconds in UTC format between a particular date in time and January 1st 1970

first, let us get our timestamp

```
ct = datetime.datetime.now()
timestamp = ct.timestamp()
print("timestamp: ", timestamp)
# timestamp: 1629731451.077646
```

we also know that the Unix timestamp is in UTC, so we might as well add it to our timezone object
```
datetime_object = datetime_object.replace(tzinfo=datetime.timezone.utc)
```

##Python time delta
As we have discussed before, the timedelta method is used to find the difference between two dates or times. It will be useful to know it.
Take a look at these examples:
count the number of days between 02-08-1996(my birthday) and today.

```
start_date = datetime.date(1996, 8, 2)
end_date = datetime.date(2021, 8, 23)

#we can simply subtract and get a timedelta object

timedelta = end_date – start_date
print(type(timedelta)) # <class 'datetime.timedelta'>
print(“Day difference: ”, timedelta.days) # Day difference: 9152
```

Another Example.
What will be the date if we add 100 days to today

```
today = datetime.date.today()
timedelta_needed = datetime.timedelta(days=100)
result_date = today + timedelta_needed
print(result_date) # 2021-12-01
```

##Python strftime() method
the strftime method helps us format date and time neatly in whichever format we need

```
now = datetime.datetime.now(tz=pytz.timezone(‘UTC’))
t = now.strftime("%H:%M:%S")
print("time: ", t) # time: 15:47:14

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
print("mm/dd/YY: ", s1)
# mm/dd/YY: 08/23/2021, 15:47:14

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
print("dd/mm/YY: ", s2)
# dd/mm/YY: 23/08/2021, 15:47:14

print(“Timezone: ”, now.strftime(“%Z”))
# Timezone: UTC

print("Weekday: ", now.strftime('%A'))
# Weekday: Monday
```

##Python strptime() method
unlike the strftime method, the strptime method takes a string and converts it into a datetime object. This method takes two parameters. Which are:
Date String
Date Format

the second parameter is the format and it refers to the format directives. We use the same directives as to the strftime method (%A,%d, %Z … etc). It specifies to the datetime string the format that needs to be processed. Let's take a look at a few examples.

```
datetime_string = '08/23/21 15:23:52'
datetime_object = datetime.datetime.strptime(datetime_string, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
# <class 'datetime.datetime'>
print(datetime_object)
# 2021-08-23 15:23:52
```

As you can see from above, the returned type is a datetime object and we can manipulate it however we want using all the datetime module's classes and methods available to us.

If you find this post useful share it with others who might need it and follow me for more posts like this also if you have any contribution or criticism you will like to share, feel free to comment. I will respond.