通常在数据科学中,我们需要基于时间值的分析。 python可以优雅地处理各种格式的日期和时间。 日期时间库提供了必要的方法和函数来处理下列情况。
接下来,我们将会逐个学习。
日期及其各个部分用不同的日期时间函数表示。 此外,还有格式说明符,它们在显示日期的字母部分(如月份或星期几的名称)中发挥作用。 以下代码显示了今天的日期和日期的各个部分。
import datetime
print 'the date today is :', datetime.datetime.today()
date_today = datetime.date.today()
print (date_today)
print ('this year :', date_today.year)
print ('this month :', date_today.month(
print ('month name:',date_today.strftime('%b'))
print ('this week day :', date_today.day))
print ('week day name:',date_today.strftime('%a'))
执行上面示例代码,得到以下结果 -
the date today is : 2018-05-22 15:38:35.835000
2018-05-22
this year : 2018
this month : 4
month name: may
this week day : 22
week day name: sunday
对于涉及日期的计算,我们将各种日期存储到变量中,并将相关的数学运算符应用于这些变量。
import datetime
#capture the first date
day1 = datetime.date(2018, 2, 12)
print ('day1:', day1.ctime())
# capture the second date
day2 = datetime.date(2017, 8, 18)
print ('day2:', day2.ctime())
# find the difference between the dates
print ('number of days:', day1-day2)
date_today = datetime.date.today()
# create a delta of four days
no_of_days = datetime.timedelta(days=4)
# use delta for past date
before_four_days = date_today - no_of_days
print ('before four days:', before_four_days )
# use delta for future date
after_four_days = date_today + no_of_days
print 'after four days:', after_four_days
执行上面示例代码,得到以下结果 -
day1: mon feb 12 00:00:00 2018
day2: fri aug 18 00:00:00 2017
number of days: 178 days, 0:00:00
before four days: 2018-04-18
after four days: 2018-04-26
日期和时间使用逻辑运算符进行比较。必须小心将日期的正确部分进行比较。 在下面的例子中,我们采用未来和过去的日期,并使用python if
子句和逻辑运算符进行比较。
import datetime
date_today = datetime.date.today()
print ('today is: ', date_today)
# create a delta of four days
no_of_days = datetime.timedelta(days=4)
# use delta for past date
before_four_days = date_today - no_of_days
print ('before four days:', before_four_days )
after_four_days = date_today + no_of_days
date1 = datetime.date(2018,4,4)
print ('date1:',date1)
if date1 == before_four_days :
print ('same dates')
if date_today > date1:
print ('past date')
if date1 < after_four_days:
print ('future date')
执行上面示例代码,得到以下结果 -
today is: 2018-04-22
before four days: 2018-04-18
date1: 2018-04-04
past date
future date