Some basic usage of python in time and datetime

About time module

In the time we have three objects in the module:

时间戳
结构化的时间对象
字符串

Usage 1: time.time ()

print(time.time())
# 用法解释:获取时间戳:从时间元年(1970.1.1 00:00:00)到现在的秒数/在其他一些语言 -- >毫秒数 --> 相差1000倍

# 输出
1584348305.7710142

Usage 2: time.gmtime ()

print(time.gmtime()) # GMT 符合欧洲那边的习惯
# 用法解释:获取格式化时间对象: 是九个字段组成的:年月日时分秒......

# 输出
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=8, tm_min=47, tm_sec=15, tm_wday=0, tm_yday=76, tm_isdst=0)
# time.struct_time -- > 结构化的时间对象

You will find this use of the abovehourData is here and we do not meet.
Since this is in line with the European side of the habit, then there is no habit of it in line with our side -> Of course yes, see Usage 3

Usage 3: time.localtime ()

Look to know the function name, local time thing

print(time.localtime())
# 用法解释:获取格式化时间对象: 是九个字段组成的:年月日时分秒......

# 输出
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=9, tm_wday=0, tm_yday=76, tm_isdst=0)

Usage 4: time.strftime ()

s = time.strftime("%Y,%m,%d %H:%M:%S")
print(s)

# 输出
2020,03,16 16:53:06

# 用法解释:格式化时间对象和字符串之间的转换,第二个参数默认是当前使用时的当前时间的格式化时间对象,如果要自己规定时间戳的话,那么我们可以这么做:
s = time.strftime("%Y,%m,%d %H:%M:%S",time.localtime(1))
print(s)

# 输出
1970,01,01 08:00:01

To sum up python in date and time format symbols:

%y 两位数的年份表示(00-99)

%Y 四位数的年份表示(000-9999)

%m 月份(01-12)

%d 月内中的一天(0-31)

%H 24小时制小时数(0-23)

%I 12小时制小时数(01-12)

%M 分钟数(00=59)

%S 秒(00-59)

 

%a 本地简化星期名称

%A 本地完整星期名称

%b 本地简化的月份名称

%B 本地完整的月份名称

%c 本地相应的日期表示和时间表示

%j 年内的一天(001-366)

%p 本地A.M.或P.M.的等价符

%U 一年中的星期数(00-53)星期天为星期的开始

%w 星期(0-6),星期天为星期的开始

%W 一年中的星期数(00-53)星期一为星期的开始

%x 本地相应的日期表示

%X 本地相应的时间表示

%Z 当前时区的名称

%% %号本身

Usage 5: time.strptime ()

s = time.strptime("2020 03 16","%Y %m %d") # --> 没给都是默认值
print(s)

# 用法解释:把时间字符串转换成时间对象(格式一定相同)

# 输出
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=76, tm_isdst=-1)

Usage 6: time.sleep ()

time.sleep(XXX)
# 用法解释:暂停当先线程XXX秒

About datetime module

import datetime

Usage 1: date class

# date类:
d = datetime.date(2010,10,10)
print(d)

# 获取date对象中的各个属性
print(d.year,d.month,d.day)

# 输出
2010-10-10
2010 10 10

Usage 2: time class

d = datetime.time(3,26,13)
print(d)
print(d.hour, d.minute, d.second)

Usage 3: datetime class (mainly used for mathematical calculations)

Prior to that date is a two usage is there is a time, which can be interpreted as a datetime combination of two

dt =datetime.datetime(2001,1,1,1,1,1)
print(dt)

The following are the specific use of this mathematical calculationsEach operation can only date datetime timedelta

# date datetime timedelta
td = datetime.timedelta(days=1)

d = datetime.datetime(2010,10,31)

res = d + td

print(res)

# 输出
2010-11-01 00:00:00
Published 12 original articles · won praise 7 · views 164

Guess you like

Origin blog.csdn.net/caiyongxin_001/article/details/104902487