What is the module/method used to get the current time?
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
This question is for Python but since Django is one of the most widely used frameworks for Python, its important to note that if you are using Django you can always use timezone.now()
instead of datetime.datetime.now()
. The former is timezone 'aware' while the latter is not.
See this SO answer and the Django doc for details and rationale behind timezone.now()
.
from django.utils import timezone
now = timezone.now()
Current time of a timezone
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
#list timezones
pytz.all_timezones
Use:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150
And just the time:
>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)
>>> print(datetime.datetime.now().time())
15:08:24.789150
See the documentation for more information.
To save typing, you can import the datetime
object from the datetime
module:
>>> from datetime import datetime
Then remove the leading datetime.
from all of the above.
I want to get the time with milliseconds. A simple way to get them:
import time, datetime
print(datetime.datetime.now().time()) # 11:20:08.272239
# Or in a more complicated way
print(datetime.datetime.now().time().isoformat()) # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str) # 11:20:08.%f
But I want only milliseconds, right? The shortest way to get them:
import time
time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751
Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:
def get_time_str(decimal_points=3):
return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
You can do so using ctime():
from time import time, ctime
t = time()
ctime(t)
output:
Sat Sep 14 21:27:08 2019
These outputs are different because the timestamp returned by ctime()
depends on your geographical location.