python中时间

from django.test import TestCase

import datetime,time


#获取当前时间的两种方法
now = time.strftime("%Y-%m-%d %H:%M:%S")
print(now) #2019-01-28 20:25:39

now = datetime.datetime.now()
print (now) #2019-01-28 20:25:39.679410


#获取当前时间前一小时、前一天、前一周、前一个月

now = datetime.datetime.now()

# 前一小时
d1 = now - datetime.timedelta(hours=1)
print(d1.strftime("%Y-%m-%d %H:%S:%M"))

# 前一天
d2 = now - datetime.timedelta(days=1)
print(d2.strftime("%Y-%m-%d %H:%S:%M"))

# 上周日
d3 = now - datetime.timedelta(days=now.isoweekday())
print(d3.strftime("%Y-%m-%d %H:%S:%M"), " ", d3.isoweekday())

# 上周一
d31 = d3 - datetime.timedelta(days=6)
print(d31.strftime("%Y-%m-%d %H:%S:%M"), " ", d31.isoweekday())

# 上个月最后一天
d4 = now - datetime.timedelta(days=now.day)
print(d4.strftime("%Y-%m-%d %H:%S:%M"))

# 上个月第一天
print(datetime.datetime(d4.year, d4.month, 1))

 

posted @ 2023-10-26 22:42  冰底熊  阅读(4)  评论(0编辑  收藏  举报