Kishore Reddy
Kishore Reddy

Reputation: 11

How to Add 10mins to a datetime in python

cdr_start_time = "12:10:13"
start_time = "00:10:00"

if cdr_start_time > start_time:
    start_time = start_time + 10

In the above code I would like to add 10mins after time comparison, how do I do in python. Thank you in advance

Upvotes: 0

Views: 202

Answers (3)

Phillip Cloud
Phillip Cloud

Reputation: 25652

In pandas you can do this with the Timestamp class, which is a subclass of datetime.datetime:

In [63]: from pandas import Timestamp

In [64]: from pandas.offsets import Minute, date_range

In [65]: pd.Timestamp('1/1/2001') + Minute(10)
Out[65]: Timestamp('2001-01-01 00:10:00', tz=None)

This extends to arrays of datetime64s too:

In [66]: date_range('1/1/2001', periods=10).to_series() + Minute(10)

Out[66]:
2001-01-01   2001-01-01 00:10:00
2001-01-02   2001-01-02 00:10:00
2001-01-03   2001-01-03 00:10:00
2001-01-04   2001-01-04 00:10:00
2001-01-05   2001-01-05 00:10:00
2001-01-06   2001-01-06 00:10:00
2001-01-07   2001-01-07 00:10:00
2001-01-08   2001-01-08 00:10:00
2001-01-09   2001-01-09 00:10:00
2001-01-10   2001-01-10 00:10:00
Freq: D, dtype: datetime64[ns]

Upvotes: 0

Ishaan
Ishaan

Reputation: 886

You can use Timedelta

from datetime import datetme,timedelta
>>> d = datetime.now()
datetime.datetime(2013, 8, 25, 12, 23, 14, 410952)

>>> d1 = d+timedelta(minutes=20)
datetime.datetime(2013, 8, 25, 12, 23, 14, 410952)

Upvotes: 0

TerryA
TerryA

Reputation: 59974

Use the datetime module:

import datetime
cdr_start_time = "12:10:13"
start_time = "00:10:00"
mydate1 = datetime.datetime.strptime(cdr_start_time, '%H:%M:%S') # Creates a datetime object
mydate2 = datetime.datetime.strptime(start_time, '%H:%M:%S')
if mydate1 > mydate2:
    mydate2 += datetime.timedelta(minutes=10) # Adds ten minutes to the datetime object

print datetime.datetime.strftime(mydate2, '%H:%M:%S') # Turns it back to a readable string

Prints:

00:20:00

Upvotes: 5

Related Questions