How to subtract 40 minutes from the current date and display the result of this calculation without seconds?

Question:

My problem is that I don’t know how to subtract 40 minutes from the current time in Python. The result of this calculation should be displayed without seconds, e.g. 30-09-2022 17-30

At the moment, the program code looks like this:

from datetime import datetime, timedelta
    
x = datetime.today() - timedelta(minutes=40)

print(x)

Unfortunately, the program does not work because it displays the date with seconds instead of without seconds

Asked By: Karol

||

Answers:

welcome to Python

If You’re using an IDE like Visual Studio Code and an extension for intellisense like Pylance You can do something like this:

from datetime import datetime, timedelta
def subtractMinutes(minutes: int = 40) -> str:
    return datetime.today()-timedelta(minutes=minutes)

Intellisense would tell You that Your function is returning a "date" object instead of a "str" object

Date objects store all information about the date, from milliseconds to years

You can set the seconds of the date object to zero, but it will still print the full date object
What You want is a string, a formatted string! So the way to fix Your function would be

from datetime import datetime, timedelta
DATE_FORMAT = "%d-%m-%Y"
def subtractMinutes(minutes: int = 40) -> str:
    ## strftime read "format date as string"
    return datetime.strftime(
        datetime.today()-timedelta(minutes=minutes),
        DATE_FORMAT
        )

For a reference to other formats You can visit this site

Happy hacking!

Answered By: dasfacc
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.