how can you print the time and date in python

时间:2015-08-07 02:32:31

标签: python datetime

I really need to figure out how to print the date and time, and I do not need the import time function, please give me the shortest way possible. Thanks.

3 个答案:

答案 0 :(得分:3)

You'll have to import something. I'd use datetime.

import datetime
## whatever code you want here
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

答案 1 :(得分:1)

http://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/

Use what you Need from

import datetime

now = datetime.datetime.now()

print
print "Current date and time using str method of datetime object:"
print str(now)

print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond

print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")

print
print "Current date and time using isoformat:"
print now.isoformat()

答案 2 :(得分:1)

您希望日期为什么格式或时区?

如果您想要当地时间,请导入time

import time
local_time = time.localtime()
time.strftime('%a, %d %b %Y %H:%M:%S', local_time)

以当地时间输出:

'Fri, 07 Aug 2015 01:08:23'

对于 UTC ,请导入datetime

import datetime
utc_time = datetime.datetime.utcnow()
utc_time.strftime("%Y-%m-%d %H:%M:%S")

以UTC时间输出:

'2015-08-07 05:06:58'