如何创建基本时间戳或日期? (蟒蛇 3.4)

新手上路,请多包涵

作为初学者,创建时间戳或格式化日期最终比我预期的更具挑战性。有哪些基本例子可供参考?

原文由 Zach Reneau 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 306
2 个回答

最终您想查看日期时间文档并熟悉格式化变量,但这里有一些示例可以帮助您入门:

 import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

输出:

时间戳:2014-10-18 21:31:12

时间戳:2014-Oct-18 21:31:12

现在日期:2014-10-18 21:31:12.318340

今天日期:2014-10-18

今天的日期是 2014 年 10 月 18 日

维护:2014 年 10 月 18 日 - 太平洋时间下午 6 点至晚上 10 点

维护:2014 年 10 月 18 日 - 中部时间下午 1 点至下午 6 点

参考链接: https ://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

原文由 Zach Reneau 发布,翻译遵循 CC BY-SA 3.0 许可协议

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

原文由 Vlad Bezden 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进