user1332577
user1332577

Reputation: 362

convert a date to a %Y:%j:%H:%M:%s in python with date command

I'm trying to convert a series of dates in python 2.6.6 with os.popen and the date command using the following call:

    t=wp.time
    dtme=os.popen("date -d t +%Y:%j:%H:%M:%S")
    dtime=dtme.read()

Where wp.time is a series of dates in the following format:

2014-07-22 19:59:53

The issue with date command is it seems to be having trouble reading the space in between the date and the yyyy-mm-dd. Is there a work around for this? What am I doing wrong in python when I do this? Is there a better way to do this? My datetime.strptime doesn't seem to be working.

Upvotes: 2

Views: 6034

Answers (3)

paisanco
paisanco

Reputation: 4164

The %j doesn't look right for reading the date format you want, that's for day of year format.

I think for strptime or strftime, you want

"%Y-%m-%d %H:%M:%s"

as your format string for something like 2014-07-22 19:59:53

Also the Linux date command would be

echo date +"%Y-%m-%d %H-%M-%S"

Or if I misunderstood you and you want to convert to day of year format, this code snippet will do it:

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

Output is

my_new_t 2014:203 19:59:53

If you want the semicolon in the output, no space do

my_new_t =datetime.datetime.strftime(thedatetime,"%Y:%j:%H:%M:%S")

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177610

Just use datetime.strptime. It is not deprecated, and it works:

>>> 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)

Note that there is a datetime class and a datetime module. That is likely the cause of the error you reported:

>>> 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>

Upvotes: 2

holdenweb
holdenweb

Reputation: 37023

Look at the subprocess library. It contains specific advice about how to replace os.popen() calls

Upvotes: 0

Related Questions