python time模块和datetime模块

时间:2021-09-24 20:00:55

time 模块

在 Python 文档里,time是归类在Generic Operating System Services中,换句话说, 它提供的功能是更加接近于操作系统层面的。通读文档可知,time 模块是围绕着 Unix Timestamp 进行的

常用操作

获取当前时间戳 time.time()

ime.time()是获取当前时间的时间戳,时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

import time

# 获区当前时间戳
time_1 = time.time()
print(time_1)
print(type(time_1))

# 1510278475.21
# <type 'float'>

datatime模块

重新封装了time模块,提供更多接口,提供的类有:date,time,datetime,timedelta,tzinfo。

常用操作

获取当前时间:datetime.now()

from datetime import datetime

now_time = datetime.now()
print(now_time)
print(type(now_time))

# 2017-11-10 09:46:05.160000
# <type 'datetime.datetime'>

过程:

1、先导入datetime类

2、通过datetime的now方法就获得当前所需要的时间

获取其它时间(昨天、明天):timedelta

from datetime import datetime, timedelta

#获取昨天的时候
now_time = datetime.now()
yesterday = now_time + timedelta(days=-1)
print(yesterday)
print(type(yesterday))


# 017-11-09 09:58:30.153000
# <type 'datetime.datetim

#获取明天的时间
now_time = datetime.now()
tomorrow = now_time + timedelta(days=+1)
print(tomorrow)
print(type(tomorrow))

# 2017-11-11 10:00:19.443000
# <type 'datetime.datetime'>

timedelta可以接收days和seconds两个参数,正数代表几天之前的,负数代表几天之前的。所以b代表的是一天之前的时间

时间格式的转换

时间的三种存在方式:时间对象,时间字符串,时间戳

(1) 字符串转datetime: datetime.strptime()

from datetime import datetime, timedelta

time_str = '2017-11-10 11:11:11'
print('time_str:{0}'.format(time_str))
print(type(time_str))
time_obj = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('time_obj :{}'.format(time_obj))
print(type(time_obj))

# time_str:2017-11-10 11:11:11
# <type 'str'>
# time_obj :2017-11-10 11:11:11
# <type 'datetime.datetime'>

(2) datetime转字符串:datetime.strftime()

from datetime import datetime, timedelta

now_time = datetime.now()
print('now_time: {0}'.format(now_time))
print(type(now_time))
str_time = datetime.strftime(now_time,'%Y-%m-%d %H:%M:%S')
print('str_time: {0}'.format(str_time))
print(type(str_time))

# now_time: 2017-11-10 10:14:35.552000
# <type 'datetime.datetime'>
# str_time: 2017-11-10 10:14:35
# <type 'str'>

(3)时间戳转时间对象:datetime.fromtimestamp()

from datetime import datetime, timedelta
import time

time_stamp = time.time()
print("time_stamp: {}".format(time_stamp))
print(type(time_stamp))

str_time = datetime.fromtimestamp(time_stamp)
print(str_time)
print(type(str_time))

# time_stamp: 1510280365.37
# <type 'float'>
# 2017-11-10 10:19:25.366000
# <type 'datetime.datetime'>