I have an int variable that are actually seconds (lets call that amount of seconds X
). I need to get as result current date and time (in datetime format) minus X
seconds.
If X
is 65 and current date is 2014-06-03 15:45:00
, then I need to get the result 2014-06-03 15:43:45
.
I'm doing this on Python 3.3.3 and I know I could probably use the datetime
module but I haven't had any success so far.
How do you subtract time from a datetime object in Python? Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. Step 2: Create an object of timedelta, to represent an interval of N hours. Step 3: Subtract the timedelta object from the datetime object.
You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.
For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.
To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.
Using the datetime
module indeed:
import datetime X = 65 result = datetime.datetime.now() - datetime.timedelta(seconds=X)
You should read the documentation of this package to learn how to use it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With