Python日期转换和检查

时间:2018-11-10 05:34:25

标签: python datetime

我希望能够将字符串转换为日期,然后执行操作以检查它是否在某个日期之前或之后。 输入格式:d / m / yyyy

6/7/2018

我想检查以上日期是否早于今天的日期10/11/2018

我该怎么做?这就是我所拥有的:

<body class="path-node page-node-type-lp navbar-is-static-top has-glyphicons">
<a href="#main-content" class="visually-hidden focusable skip-link">
    メインコンテンツに移動
</a>
<div role="main" class="main-container container js-quickedit-main-content">
    <div class="row">

        <div class="col-sm-12" role="heading">

            <section class="col-sm-12">
                <div class="row">
                    <div class="col-md-1"></div>
                    <div class="col-md-10 col-xs-12">


                        <a id="main-content"></a>
                        <div class="region region-content">
                            <article role="article" about="/myurl" class="lp full clearfix">
                                <div class="content">
                                    <div class="layout layout--onecol">
                                        <div class="layout__region layout__region--content">
                                            <section
                                                    class="block block-layout-builder block-field-blocknodelpbody clearfix">
                                                <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item">
                                                    <ol>
                                                        <li>item 1</li>
                                                        <li>item 2</li>
                                                        <li>item 3</li>
                                                    </ol>
                                                </div>
                                            </section>
                                        </div>
                                    </div>
                                </div>
                            </article>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>
</body>

如何检查日期是在特定日期(例如10/11/2018)之前还是之后?

1 个答案:

答案 0 :(得分:1)

只需使用date1 > date2

$ cat timebomb.py
#!/bin/env python

import datetime

date_format = '%d/%m/%Y'
boom_time = datetime.datetime.strptime('10/11/2018', date_format )

start_day = '01/11/2018'
day = datetime.datetime.strptime(start_day, date_format )

while day < boom_time:
    print ("Tick Tock.")
    day += datetime.timedelta(days=1)

print ("BOOM")

运行它...

$ ./timebomb.py
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
Tick Tock.
BOOM