python获取现在时间
A. python中时间如何表示
Python中有3种不同的时间表示法
1.时间戳 timestamp 是从1970年1月1日0时0分0秒开始的秒数
2.struct_time 包含9个元素的tuple
3.format time 已经格式化好便于阅读的时间
使用时间需要使用time模块
import time引入time模块
time.time()方法获取当前的时间,以timestamp的形式
>>> time.time()
1576372527.424447
time.localtime()方法:以struct_time的形式获取当前的当地时间
>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=14,
tm_hour=20, tm_min=15, tm_sec=49, tm_wday=5, tm_yday=348, tm_isdst=0)
time.gmtime()方法:以struct_time的形式获取当前的格林尼治时间
从struct_time中获取具体的年月日:
ctime.tm_year ctime.tm_mon .....
ttm_tm_isdst = 1来告知mktime()现在处于夏令时,明确使用ttm.tm_isdst = 0来告知未处于夏令时
不同时间表示法的转换
struct_time转timestamp: time.mktime(<struct_time>)
timestamp转struct_time: time.localtime(time.time())
B. python编程,使用Tkinter中的文本框显示系统时间
Python编程中,用Tkinter中的文本框获取系统当前的时间并且显示,代码如下:
importsys
fromtkinterimport*
importtime
deftick():
globaltime1
#从运行程序的计算机上面获取当前的系统时间
time2=time.strftime('%H:%M:%S')
#如果时间发生变化,代码自动更新显示的系统时间
iftime2!=time1:
time1=time2
clock.config(text=time2)
#
#
#coulse>200ms,butdisplaygetsjerky
clock.after(200,tick)
root=Tk()
time1=''
status=Label(root,text="v1.0",bd=1,relief=SUNKEN,anchor=W)
status.grid(row=0,column=0)
clock=Label(root,font=('times',20,'bold'),bg='green')
clock.grid(row=0,column=1)
tick()
root.mainloop()
C. python根据时间戳获取时分秒
时间戳可简单理解为自1970/01/01/ 00:00:00 到现在经过的秒数,如果要计算日期运算,因为涉及到润年,一般使用语言自带的库实现比较简单和高效。但如果只是取时间即时分秒,完全可以不用依赖库,通过模运算和取整运算的方式实现,并且性能比内部库函数效率更高。
运行结果,100万次
1000万次
性能快了接近200%,如果有涉及到大数据分析场景,百万甚至千万级别次的调用时,该算法还是有意义的
D. 如何在python中获得当前时间前几天的日期
很简单,下面这些代码是获取当前日期的:
importtime
now=time.time()#当前时间戳
print(now)
print(time.ctime(now))#格式化当前时间戳
print(time.localtime(now))#当前时间结构体
mon=time.localtime(now)[1]#从当前时间结构体中提取月
day=time.localtime(now)[2]#从当前时间结构体中提取日
print("当前日期:%s月%s日"%(mon,day))#打印当前月与日
最终打印出来的结过如下:
这里为了演示,将时间戳计算拆解开来了,实际使用中为了提高效率,每天86400秒直接使用。而时间结构体的生成函数也应只使用一次,将返回值赋值给变量,然后从变量中分别提取。
此外还有一点尤其需要注意,Unix时间戳与Windows下不同,单位是毫秒而不是秒,所以在linux等系统下时间差还应额外乘以1000。
E. Python获取当前时间前、后一个月的函数
这需求折腾了我半天..
import time
import datetime as datetime
def late_time(time2):
# 先获得时间数组格式的日期
#time2是外部传入的任意日期
now_time = datetime.datetime.strptime(time2, '%Y-%m-%d')
#如需求是当前时间则去掉函数参数改写 为datetime.datetime.now()
threeDayAgo = (now_time - datetime.timedelta(days =30))
# 转换为时间戳
timeStamp =int(time.mktime(threeDayAgo.timetuple()))
# 转换为其他字符串格式
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d")
return otherStyleTime
a = late_time("2019-3-30")
print(a)# 打印2018-02-28
F. python运行时间的几种方法
1.获取当前时间的两种方法:
importdatetime,time
now=time.strftime("%Y-%m-%d%H:%M:%S")
printnow
now=datetime.datetime.now()
printnow
2.获取上个月最后一天的日期(本月的第一天减去1天)
last=datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
printlast
3.获取时间差(时间差单位为秒,常用于计算程序运行的时间)
starttime=datetime.datetime.now()
#longrunning
endtime=datetime.datetime.now()
print(endtime-starttime).seconds
4.计算当前时间向后10个小时的时间
d1=datetime.datetime.now()
d3=d1+datetime.timedelta(hours=10)
d3.ctime()
注:常用的类有:datetime和timedelta二种,相互间可以加减。