Python: efficient way to convert an ambiguous clock to a temporary object?

I have a list of strings as follows:

4:00-5:00PM
11:00-2:00PM
12:00-1:00PM
11:00-1:00AM

and I'm trying to find an efficient way to create two temporary objects (I suppose this is the only way to track the time range that I will later combine with the date object). It’s clear to people what we mean, we say 11: 00-1: 00AM, but we wonder what an effective way to do this:

datetime.time(23, 0)
datetime.time(1, 0)

My current approach is to make the first time and create a version of PM and AM, accept a timedelta with the final time (as indicated) and take the shorter of the two differences so that they are correct.

+5
source share
2 answers

Here is a simple implementation.

    >>> def timeRange(timestr):
    ...     t1, t2 = timestr.split("-")
    ...     timeFormat = "%I:%M%p"
    ...     t1AM = datetime.datetime.strptime(t1 + "AM", timeFormat)
    ...     t1PM = datetime.datetime.strptime(t1 + "PM", timeFormat)
    ...     t2 = datetime.datetime.strptime(t2, timeFormat)
    ...       
    ...     if (t2 - t1AM).seconds < (t2-t1PM).seconds:
    ...         return t1AM.time(), t2.time()
    ...     else:
    ...         return t1PM.time(), t2.time()
    >>> timeRange("11:00-2:00PM")
    (datetime.time(11, 0), datetime.time(14, 0))
    >>> timeRange("4:00-5:00PM")
    (datetime.time(16, 0), datetime.time(17, 0))
    >>> timeRange("11:00-1:00AM")
    (datetime.time(23, 0), datetime.time(1, 0))
    >>> timeRange("11:00-2:00PM")
    (datetime.time(11, 0), datetime.time(14, 0))
    >>> timeRange("12:00-1:00PM")
    (datetime.time(12, 0), datetime.time(13, 0))

time, datetime, .

+3

:

  • .
  • .

, :

  • (, 11: 00-1: 00AM 11: 00-1: 00PM), "" AM/PM . AM/PM .

, 6: 00-6: 00AM (6:00 PM-6:00AM 6:00 AM-6:00AM)

, ,

  • AM- > PM (). , timedelta .

, datetime , , .

, :)

+2

All Articles