Date difference in minutes in Python

后端 未结 11 1374
谎友^
谎友^ 2020-11-28 23:03

How do I calculate the difference in time in minutes for the following timestamp in Python?

2010-01-01 17:31:22
2010-01-03 17:31:22
11条回答
  •  死守一世寂寞
    2020-11-28 23:48

    If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then

    # For difference in days:
    df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
    # For difference in seconds
    df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds
    

    Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format

    AttributeError: 'TimedeltaProperties' object has no attribute 'm8'
    

    So like mentioned by many above to get the actual value of the difference in minute you have to do:

    df['diff_in_min']=df['diff_in_seconds']/60
    

    But if just want the difference between the minute parts of the two timestamps then do the following

    #convert the timedelta to datetime and then extract minute
    df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute
    

    You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.

提交回复
热议问题