What is the module/method used to get the current time?
Because no one has mentioned it yet, and this is something I ran into recently... a pytz timezone's fromutc() method combined with datetime's utcnow() is the best way I've found to get a useful current time (and date) in any timezone.
from datetime import datetime
import pytz
JST = pytz.timezone("Asia/Tokyo")
local_time = JST.fromutc(datetime.utcnow())
If all you want is the time, you can then get that with local_time.time()
.
Do
from time import time
t = time()
t
- float number, good for time interval measurement.There is some difference for Unix and Windows platforms.
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
For this example, the output will be like this: '2013-09-18 11:16:32'
Here is the list of strftime directives.
Using pandas to get the current time, kind of overkilling the problem at hand:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
Output:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
Try the arrow module from http://crsmithdev.com/arrow/:
import arrow
arrow.now()
Or the UTC version:
arrow.utcnow()
To change its output, add .format():
arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')
For a specific timezone:
arrow.now('US/Pacific')
An hour ago:
arrow.utcnow().replace(hours=-1)
Or if you want the gist.
arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
import datetime
todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12
# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38