使用date命令在Python中将日期转换为%Y:%j:%H:%M:%s格式
我正在尝试在 Python 2.6.6 中使用 os.popen 和 date 命令来转换一系列日期,调用方式如下:
t=wp.time
dtme=os.popen("date -d t +%Y:%j:%H:%M:%S")
dtime=dtme.read()
这里的 wp.time 是一系列日期,格式如下:
2014-07-22 19:59:53
我遇到的问题是,date 命令似乎在读取日期和时间之间的空格时出现了麻烦。有没有什么解决办法?我在 Python 中做错了什么?有没有更好的方法?我的 datetime.strptime 似乎不太管用。
3 个回答
0
看看这个subprocess
库。里面有关于如何替代os.popen()
调用的具体建议。
2
只需要使用 datetime.strptime
就可以了。这个方法没有被淘汰,而且可以正常使用:
>>> from datetime import datetime
>>> t='2014-07-22 19:59:53'
>>> datetime.strptime(t,'%Y-%m-%d %H:%M:%S')
datetime.datetime(2014, 7, 22, 19, 59, 53)
请注意,datetime
有一个 类 和一个 datetime
模块。这可能就是你报告的错误的原因:
>>> import datetime
>>> datetime.strptime
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'strptime'
>>> datetime.datetime.strptime
<built-in method strptime of type object at 0x1E200528>
2
这个 %j
看起来不太适合你想要的日期格式,它是用来表示一年中的第几天的。
如果你想用 strptime
或 strftime
,你应该使用
"%Y-%m-%d %H:%M:%S"
这样的格式字符串,像是 2014-07-22 19:59:53 这样的日期时间。
另外,在Linux中使用日期命令可以这样写:
echo
date +"%Y-%m-%d %H-%M-%S"
或者,如果我理解错了,你是想转换成一年中的第几天格式,这段代码可以做到:
import datetime
t = "2014-07-22 19:59:53"
thedatetime= datetime.datetime.strptime(t,'%Y-%m-%d %H:%M:%S')
my_new_t =datetime.datetime.strftime(thedatetime,"%Y:%j %H:%M:%S")
print 'my_new_t',my_new_t
输出结果是
my_new_t 2014:203 19:59:53
如果你想在输出中加上分号,并且不留空格,可以这样写:
my_new_t =datetime.datetime.strftime(thedatetime,"%Y:%j:%H:%M:%S")