【问题标题】:How can I create basic timestamps or dates? (Python 3.4)如何创建基本时间戳或日期? (Python 3.4)
【发布时间】:2025-11-22 18:00:01
【问题描述】:

作为初学者,创建时间戳或格式化日期最终比我预期的要困难一些。有哪些基本的例子可以参考?

【问题讨论】:

    标签: datetime python-3.x datetime-format


    【解决方案1】:
    >>> import time
    >>> print(time.strftime('%a %H:%M:%S'))
    Mon 06:23:14
    

    【讨论】:

      【解决方案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-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

      【讨论】:

      • 该答案中没有时间戳。
      • 我将为 Python 3.7.3 留下一个答案:使用来自 time 包的 time.time()