使用date命令将日期转换为%Y:%j:%H:%M:%s在python中

时间:2014-07-30 02:05:40

标签: python date datetime

我正在尝试使用os.popen转换python 2.6.6中的一系列日期,并使用以下调用转换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命令的问题是它似乎无法读取日期和yyyy-mm-dd之间的空格。有没有解决这个问题?当我这样做时,我在python中做错了什么?有一个更好的方法吗?我的datetime.strptime似乎没有用。

3 个答案:

答案 0 :(得分: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")

答案 1 :(得分: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 :(得分:0)

查看subprocess库。它包含有关如何替换os.popen()调用

的具体建议