timedelta to string type in pandas dataframe

It is possible by: df[‘duration1’] = df[‘duration’].astype(str).str[-18:-10] But solution is not general, if input is 3 days 05:01:11 it remove 3 days too. So solution working only for timedeltas less as one day correctly. More general solution is create custom format: N = 10 np.random.seed(11230) rng = pd.date_range(‘2017-04-03 15:30:00′, periods=N, freq=’13.5H’) df = pd.DataFrame({‘duration’: np.abs(np.random.choice(rng, … Read more

How to add delta to python datetime.time?

datetime.time objects do not support addition with datetime.timedeltas. There is one natural definition though, clock arithmetic. You could compute it like this: import datetime as dt now = dt.datetime.now() delta = dt.timedelta(hours = 12) t = now.time() print(t) # 12:39:11.039864 print((dt.datetime.combine(dt.date(1,1,1),t) + delta).time()) # 00:39:11.039864 dt.datetime.combine(…) lifts the datetime.time t to a datetime.datetime object, the … Read more

Convert timedelta to years?

You need more than a timedelta to tell how many years have passed; you also need to know the beginning (or ending) date. (It’s a leap year thing.) Your best bet is to use the dateutil.relativedelta object, but that’s a 3rd party module. If you want to know the datetime that was n years from … Read more

Convert a timedelta to days, hours and minutes

If you have a datetime.timedelta value td, td.days already gives you the “days” you want. timedelta values keep fraction-of-day as seconds (not directly hours or minutes) so you’ll indeed have to perform “nauseatingly simple mathematics”, e.g.: def days_hours_minutes(td): return td.days, td.seconds//3600, (td.seconds//60)%60

How to construct a timedelta object from a simple string

To me the most elegant solution, without having to resort to external libraries such as dateutil or manually parsing the input, is to use datetime’s powerful strptime string parsing method. from datetime import datetime, timedelta # we specify the input and the format… t = datetime.strptime(“05:20:25″,”%H:%M:%S”) # …and use datetime’s hour, min and sec properties … Read more