How to Get Historical Dates with Datetime Module in Python


with this example, we can learn how to get historical dates with datetime module in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Import datetime module
import datetime

# Define a function to get the date before a week ago
def getWeekago():

# Get today's date
    today = datetime.date.today()

# Define the time interval, that is, the length between two time points
    oneweek = datetime.timedelta(days=7)

# Subtract the interval to get the date of one week ago
    weekago = today - oneweek

    return weekago

# Call the function
wgdate = getWeekago()
print('The date of one week ago: %s'%wgdate)

Output:

The date of one week ago: 2018-08-26
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments