Skip to main content

How to change time format in Python

In [ ]:
#Use the module datetime to extract the time and date from the header of a fits image. 
#This function converts the date from 24h format to 12h format, this is useful since 12 is usually 0 in 24h format and could be a bit irritating when computing durations.
#This could be done using the function strptime in datetime:


def 24t12(file):
    header = pyfits.getheader(file)
    date = header['DATE_OBS']
    time_24h = datetime.datetime.strptime(date,'%Y-%m-%dT%H:%M:%S.%f').time()
    d=time.strftime('%I:%M:%S.%f')  
    time_12h = datetime.datetime.strptime(d,'%H:%M:%S.%f')
    return time_12h