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

Install nornir Python Library on Ubnutu

Nornir is a Python library for automating network connected devices. You can compare it to Ansible, which is mainly used...
29/12/2020

Kivy Python Tutorial

The importance of mobile software in our world today can never be overemphasized, everyone moves about with their devices...
28/12/2020

Using Python to Zip Files

With data increasing in size exponentially every day, your concern about how to keep the said data without over-flowing...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Hướng Dẫn Chọn Dịch Vụ Thuê Địa Chỉ IPv4
10/03/2025

Reliable IPv4 and IPv6 Subnet Rental Services: The Perfect Solution for Global Businesses
23/12/2024

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024