如何在Python中打印时间和日期

3

我真的需要找出如何打印日期和时间,而且我不需要使用 import time 函数,请给我最简单的方法。谢谢。

3个回答

6

你需要引入一些东西。我会使用datetime。

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

代码似乎可以工作,谢谢。但是有没有办法将 import datetime 与其他代码片段分开放置? - Pranav Sharma
1
通常所有的导入语句都放在代码文件的顶部。导入 datetime 后,您可以在任何后续时间调用它。 - weirdev
@RBXII3 欢迎来到StackOverflow。如果有回答对您有帮助,请标记为已接受,以便其他人也可以找到并使用它。 - weirdev

6
你想要日期的格式或时区是什么?
如果你想要本地时间,请导入“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")

以协调世界时输出:

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

1

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

使用您需要的内容

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接