python 时间、日期相关代码实现
# coding=utf-8
'''
获取当前时间上一周的开始日期和结束日期
获取当前时间上一月的开始日期和结束日期
'''
import datetime
d = datetime.datetime.now()
def day_get(d):
oneday = datetime.timedelta(days=1)
day = d - oneday
date_from = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)
date_to = datetime.datetime(day.year, day.month, day.day, 23, 59, 59)
print ('---'.join([str(date_from), str(date_to)]))
def week_get(d):
dayscount = datetime.timedelta(days=d.isoweekday())
dayto = d - dayscount
sixdays = datetime.timedelta(days=6)
dayfrom = dayto - sixdays
date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print ('---'.join([str(date_from), str(date_to)]))
def month_get(d):
"""
返回上个月第一个天和最后一天的日期时间
:return
date_from: 2016-01-01 00:00:00
date_to: 2016-01-31 23:59:59
"""
dayscount = datetime.timedelta(days=d.day)
dayto = d - dayscount
date_from = datetime.datetime(dayto.year, dayto.month, 1, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print ('---'.join([str(date_from), str(date_to)]))
return date_from, date_to
week_get(d)
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
import datetime
from datetime import timedelta
def gen_dates(b_date, days):
day = timedelta(days=1)
# print(day)
for i in range(days):
# print(b_date + day*i)
yield b_date + day*i
def get_date_list(start_date, end_date): #end_date=None
"""
获取日期列表
:param start: 开始日期
:param end: 结束日期
:return:
"""
if start_date is not None:
start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
if end_date is None:
end = datetime.datetime.now()
else:
end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
# print(start, end)
# print(type((end-start).days)) # <class 'int'> 29 4-01 --> 4-30 29 天
data = []
for d in gen_dates(start, ((end-start).days + 1)): # 29 + 1
# print(d) # datetime.datetime 类型
data.append(d.strftime("%Y-%m-%d"))
'''
['2018-04-01', '2018-04-02', '2018-04-03', '2018-04-04', '2018-04-05', '2018-04-06', '2018-04-07', '2018-04-08',
'2018-04-09', '2018-04-10', '2018-04-11', '2018-04-12', '2018-04-13', '2018-04-14', '2018-04-15', '2018-04-16',
'2018-04-17', '2018-04-18', '2018-04-19', '2018-04-20', '2018-04-21', '2018-04-22', '2018-04-23', '2018-04-24',
'2018-04-25', '2018-04-26', '2018-04-27', '2018-04-28', '2018-04-29', '2018-04-30', '2018-05-01', '2018-05-02',
'2018-05-03', '2018-05-04', '2018-05-05', '2018-05-06', '2018-05-07', '2018-05-08', '2018-05-09']
'''
return data
if __name__ == '__main__':
'''
两个日期之间的所有日期,包括开始日期, 包括 结束日期
'''
start_date = '2018-04-01'
end_date = '2018-04-30'
print(get_date_list(start_date, end_date))
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
import time, datetime
def get_day_nday_ago(date, i):
# 获取指定日期前3天的日期
# print(date)
t = time.strptime(date, "%Y-%m-%d")
y, m, d = t[0:3]
Date = str(datetime.datetime(y, m, d) - datetime.timedelta(i)).split()
return Date[0]
def day_before_date(day02):
# days = ['2018-03-18', '2018-03-19', '2018-03-20', '2018-03-21', '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25', '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29', '2018-03-30', '2018-03-31','2018-04-01', '2018-04-02', '2018-04-03', '2018-04-04', '2018-04-05', '2018-04-06', '2018-04-07', '2018-04-08', '2018-04-09', '2018-04-10', '2018-04-11', '2018-04-12', '2018-04-13', '2018-04-14', '2018-04-15', '2018-04-16']
# print(day)
# a = datetime.datetime.now()
# print(a)
# b = a.strftime('%Y%m%d')
# print(b)
# day02 = b[0:4] + '-' + b[4:6] + '-' + b[6:8]
days_list = []
for i in range(0, 30): # (1, 31) 前三十天,不包括指定日期在内 (0, 30)前三十天包括指定日期在内
date02 = get_day_nday_ago(day02, i)
days_list.append(date02)
thirty_before_days = days_list[::-1]
# print(thirty_before_days)
print(days_list)
return thirty_before_days
if __name__ == '__main__':
# 指定日期前30天的所有日期
day = '2018-05-07'
day_before_date(day)
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
import calendar
def month_has_days(date):
monthRange = calendar.monthrange(int(date[0:4]), int(date[4:6]))
# print(monthRange[1])
return monthRange[1]
#输出:
#(5,30)
# 输出的是一个元组,第一个元素是月份(0-11),第二个元素是这个月的天数。
if __name__ == '__main__':
# 哪年哪月总共有多少天
date = '201801'
month_has_days(date)
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
import time
def get_moment():
print(int(round(time.time())))
print(type(int(round(time.time())))) # int
return int(round(time.time()))
def get_moment_str():
print(time.strftime("%Y-%m-%d %H:%M:%S"))
print(type(time.strftime("%Y-%m-%d %H:%M:%S"))) # str
return time.strftime("%Y-%m-%d %H:%M:%S")
if __name__ == '__main__':
# 获取当前时间 时间戳, (10位) 1531881388
# 获取当前时间 字符串 2018-07-18 10:36:27
'''
默认情况下python的时间戳是以秒为单位输出的float
通过把秒转换毫秒的方法获得13位的时间戳:round()是四舍五入。
'''
get_moment()
get_moment_str()
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
import time, datetime
def get_day_nday_ago(date, i):
# 获取指定日期前3天的日期
# print(date)
t = time.strptime(date, "%Y-%m-%d")
y, m, d = t[0:3]
Date = str(datetime.datetime(y, m, d) - datetime.timedelta(i)).split()
return Date[0]
def day_before_date(day02):
# days = ['2018-03-18', '2018-03-19', '2018-03-20', '2018-03-21', '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25', '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29', '2018-03-30', '2018-03-31','2018-04-01', '2018-04-02', '2018-04-03', '2018-04-04', '2018-04-05', '2018-04-06', '2018-04-07', '2018-04-08', '2018-04-09', '2018-04-10', '2018-04-11', '2018-04-12', '2018-04-13', '2018-04-14', '2018-04-15', '2018-04-16']
# print(day)
# a = datetime.datetime.now()
# print(a)
# b = a.strftime('%Y%m%d')
# print(b)
# day02 = b[0:4] + '-' + b[4:6] + '-' + b[6:8]
days_list = []
for i in range(1, 31): # (1, 31) 前三十天,不包括指定日期在内 (0, 30)前三十天包括指定日期在内
date02 = get_day_nday_ago(day02, i)
days_list.append(date02)
thirty_before_days = days_list[::-1]
# print(thirty_before_days)
print(days_list)
return thirty_before_days
def day_30_ago():
# 获取今天日期
today = time.strftime("%Y:%m:%d").replace(':', '-')
# print(today)
# print(type(today))
day_before_date(today)
if __name__ == '__main__':
# 指定日期前30天的所有日期
day_30_ago()
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
# coding=utf-8
'''
当前时间几小时前、几小时后的时间, 返回str类型
'''
import datetime
st = '2020-03-13 01:00:00'
# 加 8 小时
startEntryDate = (datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=480)).strftime("%Y-%m-%d %H:%M:%S")
print('startEntryDate = ', startEntryDate)
# startEntryDate = 2020-03-13 09:00:00 str
# 减 2 小时
startEntryDate = (datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=120)).strftime("%Y-%m-%d %H:%M:%S")
print('startEntryDate = ', startEntryDate)
# startEntryDate = 2020-03-12 23:00:00 str