1、字符串转换为datetime.datetime:

print(datetime.datetime.strptime("2020-07-09 18:21:17", "%Y-%m-%d %H:%M:%S"))

输出:2020-07-09 18:21:17

2、tuple、list转换为datetime.datetime:

datetime_list = [2020, 7, 10, 9, 40, 47]
datetime_tuple = (2020, 7, 10, 9, 40, 47)

print(datetime.datetime(*datetime_list))
print(datetime.datetime(*datetime_tuple))

输出:

2020-07-10 09:40:47
2020-07-10 09:40:47

3、日期加减

print(datetime.datetime.now())
print(datetime.datetime.now() + datetime.timedelta(hours=1))
print(datetime.datetime.now() + datetime.timedelta(days=1))
print(datetime.datetime.now() + datetime.timedelta(weeks=1))

输出:

2020-07-14 11:34:47.671556

2020-07-14 12:34:47.671556

2020-07-15 11:34:47.671556

2020-07-21 11:34:47.671556

4、修改时间为指定时间(查询是从00:00:00开始查询)

print((datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00"))

输出:

2020-07-15 00:00:00

5、生成10 && 13位时间戳:

print(int(datetime.datetime.now().timestamp()))
print(int(datetime.datetime.now().timestamp())*1000)
print(int(datetime.datetime(2020, 7, 10, 9, 40, 47).timestamp()))
print(int(datetime.datetime(2020, 7, 10, 9, 40, 47).timestamp())*1000)

输出:

1594698366

1594698366000

1594345247

1594345247000

6、10 or 13位时间戳转换为标准时间:

  ①10位时间戳转换为标准时间

print(datetime.datetime.fromtimestamp(1594953515))

  输出:2020-07-17 10:38:35

 

  ②13位时间戳转换为标准时间:

time_stamp = float(1594953515000/1000)
date = datetime.datetime.fromtimestamp(time_stamp)
print(date)

  输出:2020-07-17 10:38:35