-1

how to set format in date time in python.

import time

from datetime import datetime
s1=datetime.now()
print s1
time.sleep(2)
s2=datetime.now()
print s2

FMT = '%Y-%m-%d %H:%M:%s'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print tdelta
fredtantini
  • 15,966
  • 8
  • 49
  • 55

1 Answers1

1

First, you really should consider reading Python's datetime docs. I don't think that you have a formatting problem. I think that you're misusing the method. See below.

You don't actually need the datetime.strptime(s2, FMT) method, b/c it's job is to return a time object. See this answer. Yet the datetime.now() returns an object. See the docs.

Since you're working with two time objects, you can simply subtract one from the other to determine their delta.

timediff = s2 - s1
print timediff

note that (awesomely) Python transforms your datetime.datetime objects into a datetime.timedelta object. see below.

s1=datetime.now()
time.sleep(7)
s2=datetime.now()

print type(s1), type(s2)
timediff = s2 - s1
print timediff
print type(timediff)

outputs:

<type 'datetime.datetime'> <type 'datetime.datetime'>
0:00:07
<type 'datetime.timedelta'>

So yeah, Python is awesome; and reading the docs can be fun!

Community
  • 1
  • 1
Bee Smears
  • 803
  • 3
  • 12
  • 22