Sunday, September 3, 2023
HomeProgrammingSubtracting a Day from a Date in Python

Subtracting a Day from a Date in Python


Introduction

Dates are some of the troublesome ideas in programming, largely due to the numerous completely different codecs {that a} date could be represented as and the numerous completely different nuances of dates (leap years, time zones, and so on.). Due to this, date manipulations could be troublesome. So what if we have to subtract a day from a date?

This operation is sort of frequent in varied domains like knowledge evaluation, occasion scheduling, and even easy issues like calculating the day before today’s date. On this Byte, we’ll discover how one can subtract a day from a date utilizing the datetime module and Unix timestamps. We’ll additionally take a look at different date manipulations, like subtracting greater than someday.

Utilizing the datetime Module

Python’s datetime module is a robust instrument for coping with dates and occasions. To subtract a day from a date, we are able to use the timedelta object from the datetime module. This is how:

from datetime import datetime, timedelta

# As we speak's date
at present = datetime.now()

# Subtract a day
yesterday = at present - timedelta(days=1)

print("As we speak's date:", at present)
print("Yesterday's date:", yesterday)

While you run this script, it should print at present’s date and the date for the day before today.

Utilizing Unix Timestamps

One other methodology to subtract a day from a date is by utilizing uncooked Unix timestamps. A Unix timestamp is a method to monitor time as a working whole of seconds. This depend begins on the Unix Epoch on January 1st, 1970. To subtract a day, we subtract 86400 seconds (which is the equal of 24 hours) from the present timestamp.

import time

# Get the present timestamp
now = time.time()

# Subtract a day
yesterday_timestamp = now - 86400

# Convert the timestamp again to a date
yesterday = time.ctime(yesterday_timestamp)

print("Present date:", time.ctime(now))
print("Yesterday's date:", yesterday)

Once more, this code will print the present date and the date for the day before today.

Different Date Manipulations

There are numerous different date manipulations you would possibly have to carry out aside from subtracting a single day. Let us take a look at how one can subtract greater than someday from a date.

Subtracting Extra Than One Day

If you wish to subtract greater than someday, you possibly can merely change the worth of the days parameter within the timedelta object. For instance, to subtract three days from the present date:

from datetime import datetime, timedelta

# As we speak's date
at present = datetime.now()

# Subtract three days
three_days_ago = at present - timedelta(days=3)

print("As we speak's date:", at present)
print("Date three days in the past:", three_days_ago)

This script will print at present’s date and the date from three days in the past. The timedelta object is sort of versatile and can be utilized to subtract any variety of days, weeks, and even years from a date.

Subtracting a Week

For instance you’ve got a date and also you wish to discover out what the date was precisely one week in the past. Python’s datetime module makes this operation simple. This is an instance:

from datetime import datetime, timedelta

at present = datetime.now()
one_week_ago = at present - timedelta(weeks=1)

print(f"As we speak's date: {at present}")
print(f"One week in the past: {one_week_ago}")

While you run this code, you may get an output just like this:

As we speak's date: 2022-09-30 16:50:21.992728
One week in the past: 2022-09-23 16:50:21.992728

Observe: Bear in mind, the timedelta perform means that you can subtract days, seconds, microseconds, milliseconds, minutes, hours, and weeks. It does not instantly assist months or years as a consequence of their variable lengths.

Subtracting a Month

Subtracting a month from a date is a little more concerned because of the variability within the variety of days in a month. To deal with this, we are able to create a perform that checks if subtracting a day would trigger the month to alter. In that case, it should subtract a further day till it reaches the earlier month.

from datetime import datetime, timedelta

def subtract_a_month(date):
    target_month = (date.month - 1) if date.month != 1 else 12
    whereas date.month != target_month:
        date -= timedelta(days=1)
    return date

at present = datetime.now()
one_month_ago = subtract_a_month(at present)

print(f"As we speak's date: {at present}")
print(f"One month in the past: {one_month_ago}")

Working this code would possibly offer you an output like this:

As we speak's date: 2022-09-30 16:50:21.992728
One month in the past: 2022-08-30 16:50:21.992728

Conclusion

On this Byte, we have explored a number of strategies to subtract varied time durations from a date utilizing Python, together with every week and a month. Whereas Python’s datetime and calendar modules are nice instruments to have, they might not cowl each use case. For extra advanced date manipulations, think about using a library like dateutil.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments