having issues with python time object

144 views Asked by At

i am having a small program that gets time from system and dose some arithemetic on it. here is my code:

import time
import datetime
c_time = time.strftime("%H:%M;%S")

# now to convert it into time object i am using 

c_time_converted = datetime.datetime.strptime(c_time,"%H:%M;%S")

print c_time_converted

the output is of the form :

1900-01-01 11:39:40 but i want only the time part when i split and perform other operations on it i get a string returned but i need in time format so that i can perform time arethemetic

i want it in form 11: 39:40

3

There are 3 answers

3
Scott On BEST ANSWER

Just use .time():

from datetime import datetime
c_time = '2015-06-08 23:13:57'
c_time_converted = datetime.strptime(c_time,"%Y-%m-%d %H:%M:%S")
print c_time_converted
print c_time_converted.time()

prints:

2015-06-08 23:13:57
23:13:57

EDIT (addressing a comment regarding datetime)

Here is a simple example of using a difference in datetime:

from datetime import timedelta

c_time_later = '2015-06-08 23:50:21'
c_time_later_converted = datetime.strptime(c_time_later,"%Y-%m-%d %H:%M:%S")
dt = c_time_later_converted - c_time_converted
print dt  # time I was away from stackoverflow

prints: 0:36:24

now we will add dt time back to c_time above and see that we recover c_time_later:

print (c_time_converted + dt).time()

prints: 23:50:21

Or add an hour using timedelta:

print (c_time_converted + timedelta(hours=1)).time() # prints 00:13:57
2
Pankaj On

I made a minor change in your code. Please check. it will give you time only.

import time
import datetime
c_time = time.strftime("%H:%M:%S")
# now to convert it into time object i am using 
c_time_converted = datetime.datetime.strptime(c_time,"%H:%M:%S")
print c_time_converted.time()
0
Haresh Shyara On

Try to this.

import time
import datetime
c_time = time.strftime("%H:%M;%S")

c_time_converted = datetime.datetime.strptime(c_time,"%H:%M;%S")

print c_time_converted.time()

Output :

12:04:31

Get Current Date and Time.

from datetime import datetime
print datetime.now().strftime('%Y-%m-%d %H:%M:%S')

Output:

2015-06-09 12:09:09