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

  

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289158.html

(0)
上一篇 2022年9月13日
下一篇 2022年9月13日

相关推荐

发表回复

登录后才能评论