Python datetime module

28/12/2020

Working with date and time objects is one of the most common tasks I have done in the Python utility scripts I write for file manipulations like finding files older than a given date & time etc. and in many other scripts. In this lesson, we will study some simple yet effective examples with Python datetime module which can be used to get the current date, formatting date strings, understanding a past date and much more. Let’s get started.

We will work on some simple examples with Python datetime module in this section.

Python datetime now()

It is very easy to print the current date and time using the datetime module. Let’s see an example here:

import time
import datetime

print("Time since the epoch: %s", time.time())
print("Date and time now is: " , datetime.datetime.now())

Here is what we get back with this command:

Current time and date

I understand that accessing a property inside a module with same name as the module looks odd but it is what it is. It is important to note that date and time information is printed in a human-readable format.

Providing datetime format

We can also print the date and time information by passing a formatted string to strftime function as shown in the below sample progran:

import datetime

print("Date in format : " , datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))

Let’s see the output for this command:

Formatted date and time

Using datetime variables

In this section, we will see how we can use many variables provided with the datetime module to access much granular information about current instance of time. Let’s see a script which shows this information:

import datetime

print("Current year: ", datetime.date.today().strftime("%Y"))
print("Current Month of year: ", datetime.date.today().strftime("%B"))
print("Current Week number of the year: ", datetime.date.today().strftime("%W"))
print("Current Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Current Day of year: ", datetime.date.today().strftime("%j"))
print("Current Day of the month : ", datetime.date.today().strftime("%d"))
print("Current Day of week: ", datetime.date.today().strftime("%A"))

Here is what we get back with this command:

Current instance information

This shows how we can get specific details about the variables for date and time objects.

Getting Weekday for a Date

If we want to work with a past date (or even a future one), we can easily do this by passing the day, month and year of the date we want to work with in the date function:

import datetime

some_day = datetime.date(1994,5, 20) #year, month, day
print(some_day.strftime("%A"))

Let’s see the output for this command:

Certain date instance

Converting String to datetime

It is easy to convert a String to a datetime object by passing the date and the format with which this date should be interpreted:

import datetime

now = datetime.datetime.strptime("1/1/2018", "%m/%d/%Y")

print(now)
print(type(now))

Here is what we get back with this command:

Converting string to date

Conclusion

In this lesson, we looked at how we can make use of Python’s datetime module to make date objects much usable and flexible when we want to manipulate some data.

Read more Python based posts here.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Python Virtualenv Tutorial

The headaches of dependency management are common to developers. One errant update requires hours of research to correct. ...
28/12/2020

Python timeit module

Programming is not just about accomplishing a task and getting an output we intended to get. It is also about how fast...
28/12/2020

shutil module in Python

File Management and Handling file objects are considered to be one of the most tricky tasks in all programming languages....
28/12/2020