Date difference in minutes in Python

后端 未结 11 1365
谎友^
谎友^ 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:46

    As was kind of said already, you need to use datetime.datetime's strptime method:

    from datetime import datetime
    
    fmt = '%Y-%m-%d %H:%M:%S'
    d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
    d2 = datetime.strptime('2010-01-03 17:31:22', fmt)
    
    daysDiff = (d2-d1).days
    
    # convert days to minutes
    minutesDiff = daysDiff * 24 * 60
    
    print minutesDiff
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers:

    from datetime import datetime
    import time
    
    fmt = '%Y-%m-%d %H:%M:%S'
    d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
    d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
    
    diff = d2 -d1
    diff_minutes = (diff.days * 24 * 60) + (diff.seconds/60)
    
    print(diff_minutes)
    > 3043
    
    0 讨论(0)
  • 2020-11-28 23:53

    To calculate with a different time date:

    from datetime import datetime
    
    fmt = '%Y-%m-%d %H:%M:%S'
    d1 = datetime.strptime('2010-01-01 16:31:22', fmt)
    d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
    
    diff = d2-d1
    diff_minutes = diff.seconds/60
    
    0 讨论(0)
  • 2020-11-28 23:58

    Use datetime.strptime() to parse into datetime instances, and then compute the difference, and finally convert the difference into minutes.

    0 讨论(0)
提交回复
热议问题