Enthuziast
Enthuziast

Reputation: 1205

Do calculations on datetime in Python

I've been trying the following date&time operations:

import datetime
a = datetime.datetime.strptime("1899-12-30 19:45:00", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("1899-12-30 12:42:00", "%Y-%m-%d %H:%M:%S") 
print (a-b)
print (a/b)

a-b works super, but a/b crashes: TypeError: unsupported operand type(s) for /: 'datetime.datetime' and 'datetime.datetime'

Any ideas on how I can calculate relations between date&time-values? Do I need to explicitly first calculate the seconds in each variable a and b, or is there a shorter short cut?

And if I need to calculate seconds. How do I do it? I've tried

s = a.total_seconds()
which gives: AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

(I'm using Python 3.3)

Upvotes: 3

Views: 8970

Answers (3)

leeladam
leeladam

Reputation: 1758

You have to make the difference between datetime.datetime (which is an actual date and time, for example "1899-12-30 19:45:00") and datetime.timedelta (which is a period, for example "1 hour"). Note that your a-b substraction of two datetimes will result in a timedelta.

If you're calculating race times, you have to specify the start time of the race (how would you know, anyway, how long the race lasted). Then you can do

import datetime
start = datetime.datetime.strptime("1899-12-30 12:00:00", "%Y-%m-%d %H:%M:%S") # whatever the start time is
a = datetime.datetime.strptime("1899-12-30 19:45:00", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("1899-12-30 12:42:00", "%Y-%m-%d %H:%M:%S") 
print (a-b)  # it will give you the timedelta difference between racer "a" and racer "b" 
print (a-start).total_seconds()/(b-start).total_seconds() # it will give you the ratio between "a" and "b" race times

Division is not defined for datetimes. But timedelta objects have total_seconds() which give you a number (the length of period in seconds), and you can divide numbers.


In Python 3.x print is a function and thus needs parentheses, solving the AttributeError: 'NoneType' object has no attribute 'total_seconds':

print ((a-start).total_seconds()/(b-start).total_seconds())

Upvotes: 5

stupidgrass
stupidgrass

Reputation: 71

The datetime.timedelta support divide operate as shown in the manual

So, I think you should do is:

  1. Minuse the datetime.datetime.min a_interval = a - datetime.datetime.min, b_interval = b - datetime.datetime.min
  2. Start calculate: print(a_interval - b_interval) and print(a_interval / b_interval)

I hope this can help you

Upvotes: 1

crazyzubr
crazyzubr

Reputation: 1082

Number of seconds from zero date:

x = datetime.datetime(1, 1, 1, 0, 0)

print (a-x).total_seconds()

Upvotes: 0

Related Questions