Python 时间模块:datetime和time获取当前时间的方法,获取前一日时间方法

获取昨日时间:
datetime.date.today() + datetime.timedelta(-1)  
(datetime.datetime.Now() + relativedelta(days = -1)).strftime("%d")



多加(减)一分钟
(datetime.datetime.Now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-23 10:45:21
(datetime.datetime.Now()-datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-23 10:43:21

多加(减)一小时
(datetime.datetime.Now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-24 10:42:06
(datetime.datetime.Now()-datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-23 06:43:21

多加(减)一天
(datetime.datetime.Now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-24 10:43:58
(datetime.datetime.Now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%s")
2022-03-22 10:43:58

  

一、获取间的两种方式

 

import datetime
import time

time_a = datetime.datetime.Now()
print("time_a:",time_a)

time_b = time.localtime(time.time())
print("time_b:",time_b)

输出结果:
time_a: 2022-02-09 09:53:37.251435

time_b: time.struct_time(tm_year=2022, tm_mon=2, tm_mday=9, tm_hour=9, tm_min=53, tm_sec=37, tm_wday=2, tm_yday=40, tm_isdst=0)

 

 

1.datetime

import datetime

time_a = datetime.datetime.Now()

year = time_a.strftime("%Y")	#年
print("year:", year)

month = time_a.strftime("%m")	#月
print("month:", month)

day = time_a.strftime("%d")		#日
print("day:", day)

time = time_a.strftime("%H:%M:%s")		#时间
print("time:", time)

datetime_a = time_a.strftime("%Y-%m-%d, %H:%M:%s")		#日期和时间
print("date and time:",datetime_a)

输出结果:
year: 2022
month: 02
day: 09
time: 10:23:03
date and time: 2022-02-09, 10:23:03

  

2.time

import time

time_b = time.localtime(time.time())

year = time.strftime('%Y', time_b)		#年
print("year:", year)

month = time.strftime('%m', time_b)		#月
print("month:", month)

day = time.strftime('%d', time_b)		#日
print("day:", day)

time_t = time.strftime("%H:%M:%s")          #当前时间
print("time:", time_t)

datetime_b = time.strftime('%Y-%m-%d, %H:%M:%s', time_b)   #当前日期和时间
print("date and time:",datetime_b)

输出结果:
year: 2022
month: 02
day: 09
time: 10:18:41
date and time: 2022-02-09, 10:18:41

  

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...