Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python time subtraction

Tags:

python

time

I want to get the time in Python. With time.ctime(), there are lots of functions:

I tried:

def write_time():  
  NUMBER_OF_MIN=40 #my offset
  obj=time.gmtime()
  print  " D", obj.tm_mday, " M",obj.tm_mon,  "Y",obj.tm_year, 
  " time", obj.tm_hour+TIME_OFFSET,":",   obj.tm_min-NUMBER_OF_MIN, ":",obj.tm_sec

I want to subtract 40 minutes from the time.

like image 493
Tebe Avatar asked Dec 15 '12 23:12

Tebe


People also ask

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 you subtract hours and minutes in Python?

Subtract hours from given timestamp in python using relativedelta. In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has all the attributes to represent a duration i.e. Year, Month, Day, Hours, Minutes, Seconds and Microseconds.

How do you subtract two time values in Python?

For example, the %H:%M:%S format codes are for hours, minutes, and seconds. To get the difference between two-time, subtract time1 from time2.


1 Answers

Check out the datetime library, which provides much more flexibility for math using dates.

For example:

import datetime
print datetime.datetime.now()
print datetime.datetime.now() - datetime.timedelta(minutes=2)
print datetime.datetime.now() - datetime.timedelta(seconds=10)
print datetime.datetime.now() - datetime.timedelta(milliseconds=400)

Prints:

el@dev ~ $ python test.py
2014-11-26 06:47:07.179411
2014-11-26 06:45:07.179538
2014-11-26 06:46:57.179581
2014-11-26 06:47:06.779614
like image 168
acjay Avatar answered Oct 29 '22 06:10

acjay