Python 日期格式相关

简介:
+关注继续查看

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

1
2
3
4
5
6
7
8
9
10
#-*- 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)

结果如下:

1
2
3
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


日期 到 字符串:

1
2
3
4
>>> 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'

字符串 到 时间

1
2
3
4
>>> 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时间戳 到 时间

1
2
3
4
>>> 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时间戳

1
2
3
4
5
6
>>> 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

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

1
2
3
4
5
6
7
>>> 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


本文转自 nonono11 51CTO博客,原文链接:http://blog.51cto.com/abian/1606617,如需转载请自行联系原作者
相关文章
|
24天前
|
Python
Python儒略日和常规日期的转换
天文地理学科经常会使用儒略日(Julian Day) 这里使用Python的datetime模块实现其和常规日期的转换
20 0
|
26天前
|
Python
|
27天前
|
Python
|
27天前
|
Python
|
27天前
|
Python
|
28天前
|
Python
|
29天前
|
Unix Python Windows
|
2月前
|
开发工具 对象存储 Python
使用Python的SDK从OSS中下载指定日期的所有文件
使用Python的SDK从OSS中下载指定日期的所有文件
50 1
|
2月前
|
Unix Python Windows
Python 日期和时间
Python 日期和时间
|
4月前
|
API Python
32.从入门到精通:Python错误输出重定向和程序终止 字符串正则匹配 访问 互联网 日期和时间
32.从入门到精通:Python错误输出重定向和程序终止 字符串正则匹配 访问 互联网 日期和时间
相关产品
云迁移中心
推荐文章
更多