Skip to content

How to Get Today’s Date or Any Past Date in Python

This is a pretty straightforward task that can be easy to forget if you don’t use them often enough. So let’s get started.

This article will help you on how to get today’s date in Python and how to get any past or future day in Python, or in other words how to get date from a day ago, a week ago, a month ago in Python.

Suppose you want to get today’s date in datetime format, you can do the following.

import datetime

today = datetime.date.today()
print(type(today))
print(today)
<class 'datetime.date'>
2021-11-05

In case you need other dates a few days away from today, for example, how to get a date a week ago or a week later from today, you can make use of the timedelta function as provided by Python.

last_week = today - datetime.timedelta(days=7)
next_week = today + datetime.timedelta(days=7)

print("last week: ",last_week, "\ntoday: ", today, "\nnext week: ", next_week)
last week: 2021-10-29
today: 2021-11-05
next week: 2021-11-12

This function can be really useful and you can use many other time units to specify the time you need. The official documentation describes it as follows, which means you can use parameters like days, seconds, microseconds, and so on. Unluckily, there’s yet any parameter for months or years.

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

In the examples above the dates you obtain are in datetime format. If you need it in string, then you can cast it to string or you can use the following method.

import time

today = time.strftime("%Y-%m-%d")
current_time = time.strftime("%d %B %Y %H:%M:%S %Z")
print(type(today))
print(today)
print(type(current_time))
print(current_time)

<class 'str'>
2021-11-05
<class 'str'>
05 November 2021 19:06:26 SE Asia Standard Time

The %d refers to date, %B refers to the month’s full name (as opposed to %b which only refers to the month’s abbreviated name like Jan, Feb, Mar, and so on), %Y signifies year. Meanwhile, %H, %M, and %S are for hour, minute, and seconds respectively. As for %Z, it’s used to show the timezone.

It’s important to note that all of these dates and datetimes that you obtain will depend on the time on your computer.

I hope you find this short article useful. Thanks for reading!

References:

https://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-python

https://stackoverflow.com/questions/19686856/how-can-i-get-the-previous-week-in-python/19686958#19686958

https://stackoverflow.com/questions/20573459/getting-the-date-of-7-days-ago-from-current-date-in-python

https://docs.python.org/3/library/datetime.html#datetime.timedelta

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: