时间问题

2018-08-15 10:24:06 +08:00
 frmongo

1. 调试如下代码,总是报错

搜索了一顿,好像还是没明白出错原因

2. CODE

# coding=utf-8
# python2.7

from datetime import datetime
import re

t1= u"2018 年 01 月 1"
t2= u"2018 年 02 月 22"
t3= u"2018 年 3 月 37 日"




def str2digi(strin):
    m = re.match(u"(\d+)年(\d+)月(\d+)日?", strin)
    
    yearn = m.group(1)
    monthn = m.group(2)
    dayn = m.group(3)
    
    
    if len(m.group(2)) == 1:
        monthn = '0'+ monthn

    if len(m.group(3)) == 1:
        dayn = '0' + dayn

    cc = yearn + monthn + dayn
    print 'firstdata is ',cc
    print [cc]
    ee = str(cc)
    print [ee]
    
    time = datetime.strptime(ee, "%Y%m%d").date()
    return time
    

print 'time is [%s]' % str2digi(t1)
print 'time is [%s]' % str2digi(t2)
print 'time is [%s]' % str2digi(t3)

3. 输出

firstdata is  20180101
[u'20180101']
['20180101']
time is [2018-01-01]
firstdata is  20180222
[u'20180222']
['20180222']
time is [2018-02-22]
firstdata is  20180337
[u'20180337']
['20180337']
Traceback (most recent call last):
  File ".\t2.py", line 40, in <module>
    print 'time is [%s]' % str2digi(t3)
  File ".\t2.py", line 34, in str2digi
    time = datetime.strptime(ee, "%Y%m%d").date()
  File "C:\Python27\lib\_strptime.py", line 335, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 7
1728 次点击
所在节点    Python
8 条回复
frmongo
2018-08-15 10:30:44 +08:00
说明:t1 t2 t3 里没有空格,没有空格,这个是 V2EX 显示问题
aijam
2018-08-15 10:32:05 +08:00
3 月有 37 日?
frmongo
2018-08-15 10:37:22 +08:00
哈哈,我就是试试,忘了这茬
frmongo
2018-08-15 10:39:06 +08:00
我去,我真是晕了
hahastudio
2018-08-15 10:41:13 +08:00
话说回来,如果你真的确定你发帖的时候没有空格,可以 @ 一下 Livid,是不是 V2EX 自动给数字和中文之间加的空格,对 code block 也起作用了
princelai
2018-08-15 14:05:58 +08:00
如果你能保证都是中文的年月这种格式,我倒是有一个好办法

```
import arrow

t1= u"2018 年 01 月 1"
t2= u"2018 年 02 月 22"
t3= u"2018 年 3 月 27 日"
tt = [t1,t2,t3]

date_format = ['YYYY 年 M 月 D','YYYY 年 M 月 DD','YYYY 年 MM 月 D','YYYY 年 MM 月 DD']

def format_date(raw_date):
for d in date_format:
try:
dt = arrow.get(raw_date,d).date()
# if you want str date with custom format
# dt = arrow.get(raw_date,d).format('YYYY-MM-DD')
print(f'time is [{dt}]')
break
except:
continue

for t in tt:
format_date(t)
```
wlwood
2018-08-15 14:09:00 +08:00
我去,果然是时间问题。
misaka19000
2018-08-15 14:11:42 +08:00
@aijam #2 难道不是 3 月就有 37 日😂

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

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

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

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

© 2021 V2EX