标签存档: time

Python time模块

下面是几个python中常用的利用time模块对时间处理:

#!/usr/bin/python
# -*- coding=utf-8 -*-
# time

import time

# 当前时间戳
nowtime = time.time()
print nowtime

# 当前时间
print time.strftime("%Y-%m-%d %X", time.localtime())

# 将一个时间戳转换为当前时区的struct_time
nowtime = time.localtime(time.time())

# 取当前周的周一和下周一
start_tm_mday = nowtime.tm_mday - nowtime.tm_wday
starttime = str(nowtime.tm_year) + "-" + str(nowtime.tm_mon) + "-" + str(start_tm_mday) + " 00:00:00"
print starttime
end_tm_mday = start_tm_mday + 7
endtime = str(nowtime.tm_year) + "-" + str(nowtime.tm_mon) + "-" + str(end_tm_mday) + " 00:00:00"
print endtime

# 把一个格式化时间字符串转化为struct_time。和strftime()逆操作
starttime = time.strptime(starttime, "%Y-%m-%d %X")
print starttime
endtime = time.strptime(endtime, "%Y-%m-%d %X")
print endtime

# 将一个struct_time转化成时间戳
print time.mktime(starttime)
print time.mktime(endtime)

#得到当前时间前一天的时间Date型
import datetime
dt_obj = time.localtime()
datetime_obj = datetime.datetime(*dt_obj[:3])  #在参数名之前使用一个星号,就是让函数接受任意多的位置参数
yesterday = datetime_obj + datetime.timedelta(days=-1)
print yesterday
第 1 页,共 1 页1