【问题标题】:Create series of dates and times in python [duplicate]在python中创建一系列日期和时间[重复]
【发布时间】:2018-09-16 04:24:11
【问题描述】:

我想在一个月内每小时释放一次粒子,需要一个日期格式为 '2013/05/23;00:00:00:000' (YYYY/MM/DD;hh:mm:SS) 的数组:sss) 在每个步骤中都有以下小时。 所以整整一个月都是这样的:

x=['2013/05/23;01:00:00:000' '2013/05/23;02:00:00:000' '2013/05/23;03:00:00:000' ...'2013/06/23;01:00:00:000']

知道如何循环吗?谢谢!

【问题讨论】:

  • 你尝试了什么?

标签: python date time


【解决方案1】:
i = 1
x = []    
while i<=12:
    if i<10:
        str = '2013/05/23;0%d:00:00:000' % i
    else:
        str = '2013/05/23;%d:00:00:000' % i
    x.append(str)
    i=i+1

这是代码

【讨论】:

    【解决方案2】:

    有点意思

    import datetime as dt
    
    dt_start = dt.datetime(2013,5,23,1,0)
    dt_end = dt.datetime(2013,5,23,4,0)
    
    date_list = []
    while dt_start< dt_end:
      dt_start = dt_start + dt.timedelta(hours=1)
      date_list.append('{:%Y/%m/%d;%H:%M:%S:%f}'.format(dt_start))
    

    【讨论】:

    • 我会改用生成器。
    • @Marcel 知道如何使 %f 只有三个字符而不是 6 个字符吗?
    • 不幸的是,您必须对字符串进行中继才能做到这一点(最后一行):date_list.append('{:%Y/%m/%d;%H:%M:%S:%f}'.format(dt_start)[:-3])
    猜你喜欢
    • 2017-02-23
    • 2022-01-13
    • 2022-08-22
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2016-08-06
    相关资源
    最近更新 更多