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

Zac*_*eau 45 datetime datetime-format python-3.x

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

Zac*_*eau 96

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

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

时间戳:2014年10月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

  • 该答案中没有时间戳。 (2认同)

Vla*_*den 17

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
Run Code Online (Sandbox Code Playgroud)