Python 如何生成今天 0 点到现在的所有以小时为单位的时间字符串? and ...

2020-09-02 19:23:29 +08:00
 Eyon
需求:

get_today = [2020090200,2020090201,2020090202...2020090219]

get_month=[2020090100,2020090101,2020090102......2020090219]
1914 次点击
所在节点    Python
7 条回复
Trim21
2020-09-02 19:29:41 +08:00
用 datetime ( 0 点)循环加 timedelta ( hours=1 ),直到大于当前时间,然后把符合条件的的序列化成你想要的格式
Eyon
2020-09-02 23:09:43 +08:00
@Trim21 谢谢

```python

from datetime import datetime,timedelta

now = datetime.now()
thismonth_start = now.strftime('%Y%m01')
start = datetime(2020,9,1)
while True:
if start < now:
print(start.strftime('%Y%m%d%H'))
start = start+timedelta(hours=1)
```
tairan2006
2020-09-02 23:16:22 +08:00
zfill 函数了解一下
TEwrc
2020-09-03 16:37:32 +08:00
@tairan2006 看了一下没太懂 请教一下怎么用到题主说的这个问题上呢?
tairan2006
2020-09-03 17:31:25 +08:00
@TEwrc

now = datetime.now()
prefix = now.strftime('%Y%m%d')
return [prefix + str(x).zfill(2) for x in range(now.hour)]
TEwrc
2020-09-04 12:00:52 +08:00
@tairan2006 秒啊!感谢
biglazycat
2020-09-11 23:03:28 +08:00
from datetime import datetime

time_list = []
now = datetime.now()
start_day_hour = int(now.strftime('%Y%m%d00'))
stop_day_hour = int(now.strftime('%Y%m%d%H'))
for i in range(start_day_hour, stop_day_hour + 1):
time_list.append(i)

print(time_list)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/703644

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX