How to use Python to calculate time

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

For example:

Suppose now is 13:05:00

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

and I want to print the answer.

How to do this in Python?

What if the date is also included?

+6
python datetime time
source share
5 answers

datetime.timedelta is for fixed time differences (for example, 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 the addition in one go (but you can combine the date and time into a datetime object, use this, and then get the time). DST is the main culprit. For example, 12:01 am + 5 hours may be 4:01 am, 5:01 am, or 6:01 am on different days.

+10
source share

Take a look at 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 
+4
source share

There are several options for calculating dates and times, but I will write a simple way:

 import datetime import dateutil.relativedelta # current time date_and_time = datetime.datetime.now() date_only = date.today() time_only = datetime.datetime.now().time() # calculate date and time result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10) # calculate dates: years (-/+) result = date_only - dateutil.relativedelta.relativedelta(years=10) # months result = date_only - dateutil.relativedelta.relativedelta(months=10) # days result = date_only - dateutil.relativedelta.relativedelta(days=10) # calculate time result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10) result.time() 

Hope this helps

+4
source share

Take 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 quite a challenge to work with. Leap years and leap seconds are just the beginning ...

+1
source share

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

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

0
source share

All Articles