怎样转换日期格式?

2016-06-17 06:49:32 +08:00
 omg21
import time
from datetime import *
str='2016/06/10'
time_format = datetime.strptime(str, '%Y-%m-%d')
print(time_format)

我想把日期格式 2016/06/10 转换成 2016-06-10 ,可是上边的代码执行出错,为什么?
还有,‘ 16/06/10 ’如何转换成‘ 2016-06-10 ’?
3134 次点击
所在节点    Python
13 条回复
omg21
2016-06-17 06:50:47 +08:00
还有,‘ 16/06/10 ’如何转换成‘ 2016-06-10 ’?
Livid
2016-06-17 06:52:44 +08:00
你需要先把字符串转换成日期时间对象,然后再转换任何格式都会很简单。另外就是,可以看看这个库:

http://crsmithdev.com/arrow/
terence4444
2016-06-17 08:49:24 +08:00
你漏了使用 strftime 那一步
oclock
2016-06-17 09:22:10 +08:00
arrow +1
rapospectre
2016-06-17 09:56:03 +08:00
既然都是字符串为啥不直接 str.replace('/', '-')
mulog
2016-06-17 10:39:34 +08:00
人生苦短 早用 arrow 早享受。。
wowo2088
2016-06-17 11:04:18 +08:00
str.replace('/', '-') +1
hellorocky728
2016-06-17 11:14:35 +08:00
aitaii
2016-06-17 12:12:42 +08:00
字符串 直接替换就好了
wmttom
2016-06-17 12:38:02 +08:00
自从用了 arrow ,就可以手写一切时间转化了
practicer
2016-06-17 14:24:28 +08:00
t = datetime.datetime.strptime(str, '%Y/%M/%d').strftime('%Y-%M-%d')

datetime.datetime.strptime() 解析时间类字符串,返回 datetime 对象
datetime.datetime.strftime()相反,将 datetime 对象转成实践类的字符串
omg21
2016-06-17 22:41:42 +08:00
@practicer 谢谢,已经解决了,但是现在又出来一个新问题,“ 2016 年 06 月 10 日”这个怎么转成 2016-06-10 ?
practicer
2016-06-18 04:17:11 +08:00
re.sub(u'^(\d+) 年 (\d+) 月 (\d+) 日$', r'\1-\2-\3', str)
这种情况最好用 re 模块的替换函数了
r'\1-\2-\3'里面\1 \2 \3 分别表示 group(1), group(2), group(3),记得不能省略 r ,也不能省略前面 regex 语句的 u

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/286333

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX