Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract seconds from datetime in python

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.

Example

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.

Environment

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.

like image 332
rodrigocf Avatar asked Jun 03 '14 21:06

rodrigocf


People also ask

How do you subtract seconds from time in python?

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.

How do you subtract time from a datetime object in python?

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.

Can I subtract time in python?

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.

How do I convert datetime to seconds in python?

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.


1 Answers

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!

like image 161
julienc Avatar answered Sep 19 '22 11:09

julienc