Python - Date & Time Comparison using timestamps, timedelta

前端 未结 3 1764
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 20:46

I\'ve spent the past hour digging around the Python docs and many SO questions; please forgive me for being another Python newbie trapped by the mystery of time difference i

3条回答
  •  生来不讨喜
    2021-01-03 20:58

    You should be able to use

    tdelta.total_seconds()
    

    to get the value you are looking for. This is because tdelta is a timedelta object, as is any difference between datetime objects.

    A couple of notes:

    1. Using strftime followed by strptime is superfluous. You should be able to get the current datetime with datetime.now.
    2. Similarly, using time.ctime followed by strptime is more work than needed. You should be able to get the other datetime object with datetime.fromtimestamp.

    So, your final code could be

    now = datetime.now()
    then = datetime.fromtimestamp(os.path.getmtime("x.cache"))
    tdelta = now - then
    seconds = tdelta.total_seconds()
    

提交回复
热议问题