if you want your datetime.now()
precise till the minute , you can use
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
similarly for hour it will be
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')
It is kind of a hack, if someone has a better solution, I am all ears
This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"
>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'
Another similar solution:
>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'
Yes, I know I didn't get the string formatting perfect.
Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.
from datetime import datetime
Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]
If you need the values as a number just cast them as an int e.g
Hour = int(str(datetime.now())[11:13])
time.second helps a lot put that at the top of your python.
import datetime from datetime
now = datetime.now()
print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)
You can do the same with day & month etc.
Source: Stackoverflow.com