标签:
python 中 time 有三种格式:
float,
struct tuple(time.struct_time 或 datetime.datetime),
str
常用的:
float --> struct tuple: time.localtime( float )
struct tuple --> str: time.strftime(format, struct tuple)
str --> struct tuple: time.strptime(str, format)
struct tuple -- > float : time.mktime(struct tuple)
1. 当前时间
>>> import time >>> time.time() 1450681042.751 >>> time.localtime(time.time()) time.struct_time(tm_year=2015, tm_mon=12, tm_mday=21, tm_hour=15, tm_min=0, tm_sec=2, tm_wday=0, tm_yday=355, tm_isdst=0) >>> time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(time.time())) ‘2015-12-21 15:01:28‘ >>> from datetime import datetime >>> datetime.now() datetime.datetime(2015, 12, 21, 14, 58, 38, 279000) >>> datetime.today() datetime.datetime(2015, 12, 21, 14, 59, 20, 204000) >>> now = datetime.now() >>> now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond >>> now.isocalendar() # 2015年 第52周 星期一 (2015, 52, 1) >>> now.isoweekday() # 星期几,1:Monday; 而 now.weekday() 返回值从0开始 1
2. 日期字符串--> 日期
>>> s=‘2015-12-21 15:01:28‘ >>> timeArr = datetime.strptime(s, ‘%Y-%m-%d %H:%M:%S‘) datetime.datetime(2015, 12, 21, 15, 1, 28) >>> time.strftime(‘%Y/%m/%d %H:%M:%S‘, timeArr)
3. 时间戳
>>> time.mktime(time.strptime(s,‘%Y-%m-%d %H:%M:%S‘)) 1450681288.0 >>> int(time.time())
2. 日期相加减
import datetime now = datetime.datetime.now() # datetime.datetime(2015, 12, 16, 15, 6, 37, 420000) dayOfweek = datetime.datetime.isoweekday() if dayOfweek == 1: # Monday last_time = now + datetime.timedelta(days=-3) else: last_time = now + datetime.timedelta(days=-1)
标签:
原文地址:http://www.cnblogs.com/snow-backup/p/5063665.html