views:

386

answers:

4

I want to write python script that acts as a time calculator.

For example:

Suppose the time is now 13:05:00

I want to add 1 hour, 23 minutes, and 10 seconds to it.

and I want to print the answer out.

How do I do this in Python?

What if date is also involved?

A: 

Look at mx.DateTime, and DateTimeDelta in particular.

import mx.DateTime
d = mx.DateTime.DateTimeDelta(0, 1, 23, 10)
x = mx.DateTime.now() + d
x.strftime()

Keep in mind that time is actually a rather complicated thing to work with. Leap years and leap seconds are just the beginning...

retracile
+1  A: 

Look into datetime.timedelta.

Example
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)  # adds up to 365 days
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3;
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True
Alexandru
A: 

The datetime class in python will provide everything you need. It supports addition, subtraction and many other operations.

http://docs.python.org/library/datetime.html

Tim Snyder
+1  A: 

datetime.timedelta is designed for fixed time differences (e.g. 1 day is fixed, 1 month is not).

>>> import datetime
>>> t = datetime.time(13, 5)
>>> print t
13:05:00
>>> now = datetime.datetime.now()
>>> print now
2009-11-17 13:03:02.227375
>>> print now + datetime.timedelta(hours=1, minutes=23, seconds=10)
2009-11-17 14:26:12.227375

Note that it doesn't make sense to do addition on just a time (but you can combine a date and a time into a datetime object, use that, and then get the time). DST is the major culprit. For example, 12:01am + 5 hours could be 4:01am, 5:01am, or 6:01am on different days.

Roger Pate