Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python中如何计算两个日期之间的天数?

$
0
0

=Start=

缘由:

在程序中用到和日期相关的循环时,可能会需要提前确定两个日期之间的天数;还有就是在日常的一些记录中也会想了解两个日期之间的天数;总之,这样的需求是很多的。

正文: 参考解答:

>>> from datetime import date

>>> a = date( 2011 , 11 , 24 )

>>> b = date( 2011 , 11 , 17 )

>>> a-b

datetime.timedelta( 7 )

>>> (a-b).days 7

&

alias days='python -c " import sys; from datetime import date; \

print (date(*map( int , sys.argv[ 2 ].split(\ "-\"))) - date(*map(int, sys.argv[1].split(\"-\")))).days" ' $ vim ~/.zshrc $ source ~/.zshrc

$ days 2016 - 12 - 4 2016 - 12 - 10

6

$ days 2016 - 1 - 1 2016 - 12 - 11

345

本来Python部分的代码是非常简单易懂的,但是在应用到alias的时候还是碰到了不少问题,可能是因为好久没碰代码了的缘故,对部分函数的特性不够熟悉导致。

string.split()函数只能指定一个字符/字符串作为分隔符;(如果想指定多个分隔符,需要用re模块的re.split()函数 # http://stackoverflow.com/a/1059601 ) datetime.date()函数只能接收3个int/long型的参数,而string.split()函数返回的是字符串型list,需要显示类型转换成int/long型; map()函数的使用比较灵活,但在这里只需记住一点,接收list并对其中的每一个元素进行操作后,返回的也是list,需要unpack之后才能给datetime.date()函数使用; 最后一点就是,要对string.split()函数里面的双引号进行转义,否则会报错。 参考链接: http://stackoverflow.com/questions/151199/how-do-i-calculate-number-of-days-betwen-two-dates-using-python http://stackoverflow.com/questions/8258432/days-between-two-dates-in-python http://stackoverflow.com/questions/24268554/python-how-to-calculate-number-of-days-between-2-dates http://stackoverflow.com/questions/4998629/python-split-string-with-multiple-delimiters http://stackoverflow.com/questions/1059559/python-split-strings-with-multiple-delimiters http://stackoverflow.com/questions/10351772/converting-list-of-string-to-list-of-integer

=END=


Viewing all articles
Browse latest Browse all 9596

Trending Articles