from datetime import datetime
import random
gmt_format = '%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)'
print(datetime.now().strftime(gmt_format) + str(random.random()))
# Sat Apr 30 2022 15:06:03 GMT+0800 (中国标准时间)0.23243302776998054
import time
time_stamp = int(time.time()) # 10位长度时间戳
format_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_stamp))
print(format_time) # 2022-04-30 15:15:36
import time
time_arr = time.strptime('2019-06-03 21:19:03', "%Y-%m-%d %H:%M:%S")
time_tmp = time.mktime(time_arr) # 时间戳
print(int(time_tmp))
import datetime
def set_date_range(days_num):
"""
设置日期范围
:return:返回日期列表,类似这种:['2019-09-10', '2019-09-09', '2019-09-08']
"""
date_range = list()
for num in range(days_num):
str_day = str(datetime.date.today() - datetime.timedelta(days=num))
date_range.append(str_day)
return date_range
print(set_date_range(5))
# ['2022-04-30', '2022-04-29', '2022-04-28', '2022-04-27', '2022-04-26']
import datetime
_days_num = 1
_days_num = 1
# 今天
now_date = str(datetime.date.today())
print(now_date)
# 昨天
before_date = str(datetime.date.today() - datetime.timedelta(days=_days_num))
print(before_date)
# 明天
after_date = str(datetime.date.today() + datetime.timedelta(days=_days_num))
print(after_date)
import datetime
def conversion_date(dates: int):
"""
定义转化日期戳的函数,dates为excel日期数字42380
:param dates:
:return:
"""
delta = datetime.timedelta(days=dates)
# 将1899-12-30转化为可以计算的时间格式并加上要转化的日期戳
today = datetime.datetime.strptime('1899-12-30', '%Y-%m-%d') + delta
return datetime.datetime.strftime(today, '%Y-%m-%d')
print(conversion_date(42380)) # 2016-01-11
import datetime
def diff_time(time_1, time_2, fmt='%Y-%m-%d'):
"""
比较两个日期大小
:param time_1: 日期 2019-01-11
:param time_2: 日期 2019-01-11
:param fmt: 日期格式
:return: time_1 大于 time_2 则返回True
"""
if datetime.datetime.strptime(time_1, fmt) > datetime.datetime.strptime(time_2, fmt):
return True
# return False
print(diff_time('2019-01-11', '2022-01-11'))
print(diff_time('2024-01-11', '2022-01-11'))
import time
time_arr = time.strptime('2019-06-03 21:19:03', "%Y-%m-%d %H:%M:%S")
time_tmp = time.mktime(time_arr) # 时间戳
print(int(time_tmp))