简体   繁体   中英

How to compare datetime with current date?

I have the following with me

    >>> import datetime 
    >>>
    >>> some_date = datetime.datetime.strptime('2017-07-03T20:35:45.000Z', '%Y-%m-%dT%H:%M:%S.%fZ') 
    >>> some_date 
    datetime.datetime(2017, 7, 3, 20, 35, 45) 
    >>> datetime.datetime.now() 
    datetime.datetime(2017, 8, 21, 22, 4, 20, 215391) 
    >>>

I wanted to find out whether some_date is N days older than today or not? Like lets' take N as 2. Then I wanted to find whether some_date came two days ago or not. How should I subtract both? Would this work? https://stackoverflow.com/a/441152/3834059

you can check it like this
you dont need to str time

import datetime

if my_time == datetime.timedelta(days=2):
    print("my time is for 2 days ago")

or another examples for past times

import datetime

if my_time >= datetime.datetime.now() - datetime.timedelta(days=1):
    print("my time is in past")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM