Python Tutorial (33) - Example: Get the time a few days ago

Time: Column:Python views:293

Calculate a Date from Days Ago and Convert to a Specified Format

In Python, you can calculate a date from a given number of days ago and convert it to a specified format using the datetime and time modules. Below are two examples demonstrating how to do this.

Example 1: Calculate Three Days Ago

import time
import datetime

# Get the date from three days ago in datetime format
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days=3))

# Convert the datetime to a timestamp
timeStamp = int(time.mktime(threeDayAgo.timetuple()))

# Convert the datetime to a formatted string
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)

Output:

2024-09-09 18:06:08

In this example, the script calculates the date from three days ago, converts it into a timestamp, and then formats it into a string in the YYYY-MM-DD HH:MM:SS format.

Example 2: Calculate a Date Based on a Given Timestamp

import time
import datetime

# Given timestamp (e.g., 1557502800)
timeStamp = 1725900000

# Convert the timestamp to a datetime object
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)

# Calculate the date from three days ago based on the timestamp
threeDayAgo = dateArray - datetime.timedelta(days=3)
print(threeDayAgo)

Output:

2024-09-09 15:40:00

In this second example, a specific timestamp is provided. The script then calculates the date from three days before that timestamp and outputs it in YYYY-MM-DD HH:MM:SS format.