python判断今天周几_如何用python判断今天是星期几

  • Post author:
  • Post category:python


5dd88bc8ba473348.gif

本文利用Python计算今天日期、明天日期、和昨天日期的相关方法,及获取当前日期是星期几。

python编程操作日期时间主要用到的python模块是datetime和time这2个模块

获取星期几from datetime import datetime, date

dayOfWeek = datetime.now().weekday()

print(dayOfWeek)

dayOfWeek = datetime.today().weekday()

print(dayOfWeek)

注意:datetime类的weekday()方法可以获得datetime是星期几,注意weekday()返回的是0~6,是星期一到星期日。

python获取今日日期import datetime

today = datetime.date.today()

print(today)

输出:2019-06-25

python获取昨日日期import datetime

today = datetime.date.today()

zuotian = today- datetime.timedelta(days=1)

print(zuotian)

获取明天日期import datetime

today = datetime.date.today()

tomorrow = today + datetime.timedelta(days=1)

print(tomorrow)

获取后天日期import datetime

today = datetime.date.today()

tomorrow = today + datetime.timedelta(days=2)

print(tomorrow)

小结:不管是往前计算还是往后计算,直接在今日日期上进行天数的相加减