Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Time library in python

  1. Feb 12, 2010 #1
    Currently I have a program in which I want to compare times. I have

    dt = datetime.now()

    x = dt.time()

    which gives me the current time in Hours:Minutes:Seconds:MicroSeconds.

    I also have variables HourStart, MinuteStart, HourEnd,MinuteEnd. Which are the hours and minutes that are the bounds of my program running.

    I want to compare times. So I want to convert HourStart MinuteStart etc to time types. So if HourStart = 10 and MinuteStart = 30. I want to represent that as a time type being 10:30:00:000000

    any help is appreciated
  2. jcsd
  3. Feb 12, 2010 #2
    The python datetime docs is full of info and examples. Generally, the docs are the best place to start looking for info on how to do anything.
  4. Feb 12, 2010 #3
    Unless I've got the wrong end of the stick, this appears to be very straightforward. Suppose that we have ints start_hour, start_min, end_hour, and end_min. You can construct time objects from these by calling the datetime.time constructor:

    Code (Text):

    start_time = datetime.time(start_hour, start_min)
    end_time  = datetime.time(end_hour, end_min)
    You can then compare these to the time portion of a datetime.date object. For instance, if you define dt = datetime.now(), you can determine whether the end time is before now by

    Code (Text):

    end_time < dt.time()
  5. Feb 12, 2010 #4
    You've most likely got it right. I tried that already but I think I was having a lot of trouble with my libraries and how I'm calling my objects. I'll give it a shot
  6. Feb 12, 2010 #5
  7. Feb 13, 2010 #6

    This could be one of several things. Could you post your code here so I can have a look?
  8. Feb 17, 2010 #7
    As of right now I don't have much of a code, but my issue is outside of the rest of my code anyways. I have a function that returns two floats, starttime and endtime.

    basically what im doing is this:

    from datetime import *


    while starttime < float(dt.strftime('%H')) + float(dt.strftime('%M')/60) < endttime:

    so what I want to do is convert all of those floats into a datetime, for a more seemless comparison. thanks
  9. Feb 17, 2010 #8
    I was able to use dt.time() to convert it to something like hours:minutes:seconds.microseconds, which works well for my purposes. But its quite annoying when i try to convert my floats into time format. thanks again.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook