What is the module/method used to get the current time?
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
Do dir(date)
or any variables including the package. You can get all the attributes and methods associated with the variable.
You can use this function to get the time (unfortunately it doesn't say AM or PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:
Hour:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
Minute:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
Second:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
Millisecond:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
This is what I ended up going with:
>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'
That outputs the current GMT in the specified format. There is also a localtime() method.
This page has more details.
.isoformat()
is in the documentation, but not yet here
(this is mighty similar to @Ray Vega's answer):
>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
datetime.now()
returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used:
from datetime import datetime
utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417
Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):
from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00