V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Eyon
V2EX  ›  Python

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

  •  
  •   Eyon · 2020-09-02 19:23:29 +08:00 · 1882 次点击
    这是一个创建于 1304 天前的主题,其中的信息可能已经有所发展或是发生改变。
    需求:

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

    get_month=[2020090100,2020090101,2020090102......2020090219]
    7 条回复    2020-09-11 23:03:28 +08:00
    Trim21
        1
    Trim21  
       2020-09-02 19:29:41 +08:00 via Android
    用 datetime ( 0 点)循环加 timedelta ( hours=1 ),直到大于当前时间,然后把符合条件的的序列化成你想要的格式
    Eyon
        2
    Eyon  
    OP
       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
        3
    tairan2006  
       2020-09-02 23:16:22 +08:00 via Android
    zfill 函数了解一下
    TEwrc
        4
    TEwrc  
       2020-09-03 16:37:32 +08:00
    @tairan2006 看了一下没太懂 请教一下怎么用到题主说的这个问题上呢?
    tairan2006
        5
    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
        6
    TEwrc  
       2020-09-04 12:00:52 +08:00
    @tairan2006 秒啊!感谢
    biglazycat
        7
    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)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2742 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:25 · PVG 20:25 · LAX 05:25 · JFK 08:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.