Search code examples
pythondatedecimalastronomy

Convert Date (YYYY MM DD HH:MM:SS) to Decimal Day (YYYY MM DD.ddddd)


I have a script built that takes a date and time of an observation at a telescope and converts it to just a date with a decimal day. This script also takes in half the exposure time and adds it to the decimal day so that I can get the most accurate astrometric calculation. This is then submitted to The Minor Planet Center that only accepts the time of observation in Year Month Day.XXXXX What is the most accurate way to 5 decimal points to do this? This is the current way I use, yes it is very messy but it does get me the decimal day. Occasionally it is off by one second in the time conversion.

expmpc = float.("10")
utcstartmpc = "05:45:19.03"
datempc = "2015-02-14"


ddexposure = expmpc/(60.0*60.0*24.0)
ddexposure = round(ddexposure, 5)
seconds = int(utcstartmpc[6:8]) / 60.0
minutes = (int(utcstartmpc[3:5]) + seconds) / 60
hours = (int(utcstartmpc[:2]) + minutes) / 24
hours = round(hours, 5)
expadd = str(hours + ddexposure)
datempc = datempc.replace("-", " ")
utcmpc = "C%s%s" % (datempc, expadd[1:])
utcmpc = utcmpc.ljust(17, "0")

As you can see this is very messy and it involves rounding a lot of data and I believe I am losing accuracy with the rounding. The finished outcome of the code leaves a time such as this: C2015 02 14.23986

Is there a module that works better?

Thank you for the help.


Solution

  • Here's something that uses more of the built-in time/date modules (and I think it does what you want):

    import time
    import datetime
    
    def my_date_converter(date_in):
        parse_str, _ = date_in.split(".")
        date_str, time_str = parse_str.split(" ")
        parsed_time = time.strptime(time_str, "%H:%M:%S")
        total_seconds = datetime.timedelta(hours=parsed_time.tm_hour,minutes=parsed_time.tm_min,seconds=parsed_time.tm_sec).total_seconds()
        seconds_in_day = 86400.0
        decimal_seconds = total_seconds / seconds_in_day
        utcmpc = "C%s%s" % (date_str.replace("-", " "), str(round(decimal_seconds, 5))[1:])
        utcmpc = utcmpc.ljust(17, "0")
        return utcmpc
    
    
    def main():
        to_convert = "2015-02-14 05:45:19.03"
        converted = my_date_converter(to_convert)
        print "%s => %s" % (to_convert, converted)
    
    if __name__ == '__main__':
        main()
    

    Example output: 2015-02-14 05:45:19.03 => C2015 02 14.23980