python操作时间

python操作时间

import time

import datetime

#strimg--->>datetime

date = "2015-11-25 11:55:03"

new_time=datetime.datetime.strptime(date,'%Y-%m-%d %H:%M:%S')

#datetime--->>strimg

new_time.strftime("%Y-%m-%d")

#时间戳--->>string

time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time_new))

#datetime--->>时间戳

time.mktime(datetime.datetime.now().timetuple())

 

1:根据当前时间获取当天的起始和结束时间(00:00:00——23:59:59):

now = time.time()

start_time = int(now - (now % 86400) + time.timezone)

end_time = start_time + 86399

 

2:根据当前时间获取当周的起始和结束时间(周一00:00:00——周日23:59:59):

 

now = date.today()

# 获取当天是周几

week = int(now.isoweekday())

# 获取当周的第一天,也就是星期一

now_int = time.time()

start_time = int(now_int - (now_int % 86400) + time.timezone)

start_week = start_time-(week - 1)*86400

# 获取当周的最后一天,也就是星期日

end_week =  start_time+(7-aweek)*86400

 

3:根据当前时间获取当月的起始和结束时间(1号:00:00:00——月末:23:59:59)

# 获取当月第一天

import calendar

now=datetime.date.today().replace(day=1)

start_month = int(time.mktime(now.timetuple()))

# 获取当月最后一天

calendar_info = calendar.monthrange(now.year,now.month)

mystr="%s-%s-%s 23:59:59"%(now.year,now.month,calendar_info[1])

new_time=datetime.datetime.strptime(mystr,'%Y-%m-%d %H:%M:%S')

end_month = int(time.mktime(new_time.timetuple()))

以上是 python操作时间 的全部内容, 来源链接: www.h5w3.com/116192.html

回到顶部