码迷,mamicode.com
首页 > 编程语言 > 详细

Python 日期格式相关

时间:2015-01-21 20:27:54      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:python time datetime unixtimestamp

今天看网上一个说中文日期的问题. 自己试了下.

#-*- coding: gb2312 -*-
import datetime, time

#now = time.strftime(‘%Y年%m月%d日 %H时%M分%S秒‘, time.localtime()).decode(‘utf-8‘)
now = time.strftime(‘%Y年%m月%d日 %H时%M分%S秒‘, time.localtime())
print now

now = time.strptime(now, ‘%Y年%m月%d日 %H时%M分%S秒‘)
print now
print time.strftime(‘%Y-%m-%d %H:%M:%S‘, now)

结果如下:

2015年01月21日 14时22分12秒
time.struct_time(tm_year=2015, tm_mon=1, tm_mday=21, tm_hour=14, tm_min=22, tm_sec=12, tm_wday=2, tm_yday=21, tm_isdst=-1)
2015-01-21 14:22:12


日期 到 字符串:

>>> time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime())
‘2015-01-21 14:32:31‘
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
‘2015-01-21 14:33:38‘

字符串 到 时间

>>> time.strptime("2015-1-2 11:22:33", ‘%Y-%m-%d %H:%M:%S‘)
time.struct_time(tm_year=2015, tm_mon=1, tm_mday=2, tm_hour=11, tm_min=22, tm_sec=33, tm_wday=4, tm_yday=2, tm_isdst=-1)
>>> datetime.datetime.strptime("2015-1-2 11:22:33", ‘%Y-%m-%d %H:%M:%S‘)
datetime.datetime(2015, 1, 2, 11, 22, 33)

unix时间戳 到 时间

>>> time.localtime(1234567890)
time.struct_time(tm_year=2009, tm_mon=2, tm_mday=14, tm_hour=7, tm_min=31, tm_sec=30, tm_wday=5, tm_yday=45, tm_isdst=0)
>>> datetime.date.fromtimestamp(1234567890)
datetime.date(2009, 2, 14)

时间 到 unix时间戳

>>> int(time.time())
1421822833
>>> time.mktime(datetime.date(2015,1,21).timetuple())
1421769600.0
>>> time.mktime(time.strptime("2015-1-21", "%Y-%m-%d"))
1421769600.0

日期加减. 日期要格式化为时间元组才可以加减. 

>>> datetime.datetime.now() #今天
datetime.datetime(2015, 1, 21, 14, 53, 43, 321906)
>>> (datetime.datetime.now() - datetime.timedelta(days=3)).day #3天前
18
#timedelta支持的单位 days, seconds, microseconds, milliseconds, minutes, hours, weeks
>>> (datetime.datetime.now() - datetime.timedelta(weeks=1)).day
14


Python 日期格式相关

标签:python time datetime unixtimestamp

原文地址:http://abian.blog.51cto.com/751059/1606617

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!