Python人类可读日期差异 [英] Python human readable date difference

查看:160
本文介绍了Python人类可读日期差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经给出了这样的日期字符串:

I have given date strings like these:

Mon Jun 28 10:51:07 2010
Fri Jun 18 10:18:43 2010
Wed Dec 15 09:18:43 2010

什么是一个方便的python方法来计算天的差异?假设时区是一样的。

What is a handy python way to calculate the difference in days? Assuming the time zone is the same.

这些字符串由linux命令返回。

The strings were returned by linux commands.

编辑谢谢你,很多好的答案

Thank you, so many good answers

推荐答案

#!/usr/bin/env python

import datetime

def hrdd(d1, d2):
    """
    Human-readable date difference.
    """
    _d1 = datetime.datetime.strptime(d1, "%a %b %d %H:%M:%S %Y")
    _d2 = datetime.datetime.strptime(d2, "%a %b %d %H:%M:%S %Y")
    diff = _d2 - _d1
    return diff.days # <-- alternatively: diff.seconds 

if __name__ == '__main__':
    d1 = "Mon Jun 28 10:51:07 2010"
    d2 = "Fri Jun 18 10:18:43 2010"
    d3 = "Wed Dec 15 09:18:43 2010"

    print hrdd(d1, d2)
    # ==> -11
    print hrdd(d2, d1)
    # ==> 10
    print hrdd(d1, d3)
    # ==> 169
    # ...

这篇关于Python人类可读日期差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆