Python 时间模块datetime常用操作

测试的时间为:2018-10-31 晚7点左右

获取当前datetime

# 获取当前时间
now = datetime.datetime.now()
print now               # 2018-10-31 19:53:05.507000
print now.day           # 31        几号
print now.month         # 10        几月
print now.year          # 2018      哪一年
print now.hour          # 19        时
print now.minute        # 53        分
print now.second        # 5         秒
print now.microsecond   # 507000    毫秒

获取当前date

# 获取当前日期
date_today = datetime.date.today()
print date_today        # 2018-10-31    日期
print date_today.day    # 31            天
print date_today.month  # 10            月
print date_today.year   # 2018          年

获取明天/前n天

# 获取明天/前N天
today = datetime.date.today()
# 明天
tomorrow = today + datetime.timedelta(days=1)
# 前3天
pre_n_day = today - datetime.timedelta(days=3)
print today          # 2018-10-31
print tomorrow       # 2018-11-01
print pre_n_day      # 2018-10-28

获取两个datetime的时间差

# 获取时间差
pre_time = datetime.datetime(2018, 9, 10, 6, 0, 0)  # 年月日时分秒
now = datetime.datetime.now()

total_days = (now - pre_time).days          # 相差的天数
total_seconds = (pre_time - now).seconds    # 相差的秒数

print now - pre_time        # 51 days, 14:18:12.272000
print total_days            # 51
print total_seconds         # 34907

获取本周/本月/上月最后一天

 

# 获取本周最后一天日期
today = datetime.date.today()
sunday = today + datetime.timedelta(6 - today.weekday())
print sunday                # 2018-11-04

# 获取本月最后一天
today = datetime.date.today()
_, month_total_days = calendar.monthrange(today.year, today.month)
month_last_day = datetime.date(today.year, today.month, month_total_days)
print month_last_day        # 2018-10-31

# 获取上个月的最后一天
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
pre_month_last_day = first - datetime.timedelta(days=1)
print pre_month_last_day    # 2018-09-30

 

参考资料:

timedelta 相关

 https://www.cnblogs.com/zknublx/p/6017094.html

calendar 相关

https://www.cnblogs.com/keqipu/p/7228502.html

其他

https://blog.csdn.net/u010541307/article/details/53162227

https://www.cnblogs.com/sunshine-blog/p/8477893.html

 

posted @ 2018-10-31 20:35  Fixdq  阅读(3000)  评论(0编辑  收藏  举报