-2

I was wondering how can I calculate the time difference between two times which have PM and AM next to them for example. I have 12:16:44 pm and 01:01:45 pm but when I use this code:

from datetime import datetime
from datetime import timedelta

s1=12:16:44
s2=01:01:45
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2), FMT) - datetime.strptime(s1), FMT)
if tdelta.days < 0:
    tdelta = timedelta(days=0,
                       seconds=tdelta.seconds,
                       microseconds=tdelta.microseconds)

but this is the output I get 12:16:44 | 01:01:45 | Time Difference: -1 day, 12:45:01 but they are both PM values? Thanks

Kijewski
  • 25,517
  • 12
  • 101
  • 143
Dabn as
  • 1
  • 2
  • To take into account possible utc offset changes e.g., due to DST transitions, see [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/a/26313848/4279) – jfs Jul 09 '15 at 19:30

1 Answers1

1

In Python, %H means 24 hour time format. %I is 12 hour format and even then you should specify PM in the string

Try that (and fix syntax errors):

s1='12:16:44 PM' 
s2='01:01:45 PM' 
FMT = '%I:%M:%S %p' 
Petar Donchev
  • 399
  • 4
  • 9