微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐