tamus tamus - 28 days ago 13
Python Question

Python - how to produce time in format 08:09:00 instead of 1900-01-01 08:09:00

this adds 30 minutes to the time such as 07:39

HOUR_ON = datetime.time(int(array_on[0]), int(array_on[1]))
HOUR_ON = str(HOUR_ON)
a = datetime.datetime.strptime(HOUR_ON,'%H:%M:%S')
HOUR_ON = a + datetime.timedelta(0,1800) # 1800 (30 mins) open door 30 mins later


but gives me "1900-01-01 08:09:00". How do I get it to give "08:09:00"

The important thing for me is the format - the code works and adds 30 minutes (as has been pointed out) I want to remove "1900-01-01" from this and leave only 08:09:00. I can't get strptime to work to do this. HOUR_ON will print 07:39 before I use

HOUR_ON = str(HOUR_ON)


when I have finished though I want "08:09:00". thanks

Addition

if update the code to

HOUR_ON = datetime.time(int(array_on[0]), int(array_on[1]))
HOUR_ON = str(HOUR_ON)
a = datetime.datetime.strptime(HOUR_ON,'%H:%M:%S')
HOUR_ON = a + datetime.timedelta(0,1800) # 1800 (30 mins) open door 30 mins later
HOUR_ON.strftime('%H:%m:%S')
print HOUR_ON


I still get 1900-01-01 08:09:00

Answer

This code is tested on both python 2 and python 3:

import datetime

#define the input time string
input_time_string = '23:39:00'
time_format_string = '%H:%M:%S'
print('input time string = {time}'.format(time=input_time_string))

#define a magic number that will be used by timedelta
seconds_in_30_minutes = 1800

#create a datetime object initialized to the time provided by the input time
#string defined above
datetime_obj = datetime.datetime.strptime(input_time_string, time_format_string)

#add 1800 seconds to the datetime object
datetime_obj_plus_30_minutes = datetime_obj + datetime.timedelta(0, seconds_in_30_minutes)

#format the datetime object as a string containing only the time
output_time_string = datetime_obj_plus_30_minutes.strftime(time_format_string)

#print the time string
print('output time string = {time}'.format(time=output_time_string))

The above code prints the following to standard output showing that it works even when the next day is fewer than 30 minutes after the input time:

input time string = 23:39:00
output time string = 00:09:00
Comments