31

I want to convert a string like this "29-Apr-2013-15:59:02" into something more usable.

The dashes can be easily replaced with spaces or other characters. This format would be ideal: "YYYYMMDD HH:mm:ss (20130429 15:59:02)".

Edit:

Sorry, I did not specifically see the answer in another post. But again, I'm ignorant so could have been looking at the solution and didn't know it. I've got this working, but I wouldn't consider it "pretty."

#29-Apr-2013-15:59:02

import sys, datetime, time

#inDate = sys.argv[1]
inDate = 29-Apr-2013-15:59:02

def getMonth(month):
    monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
    for k, v in monthDict.iteritems():
        if month == k:
            return v

day = inDate[:2]
#print day
month = inDate[3:6]
#print month
year = inDate[7:11]
#print year
time = inDate[-8:]
#print time

newDate = year+getMonth(month)+day
newDateTime = newDate+" "+time

print newDate
print newDateTime

Any thoughts on improving?

Bryan
  • 14,775
  • 6
  • 46
  • 75
dgj32784
  • 463
  • 1
  • 4
  • 12
  • 7
    Have you read the [`strftime()` and `strptime()` behavior](http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) documentation? there are examples there that should help you. – David Cain Apr 29 '13 at 19:50
  • 1
    @Andbdrew -- Careful: http://meta.stackexchange.com/questions/172758/what-have-you-tried-epidemic – mgilson Apr 29 '13 at 19:51
  • I would try adjusting how you are getting that date string if possible – cmd Apr 29 '13 at 19:58
  • possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – tripleee Jun 23 '15 at 03:36

3 Answers3

51

Use datetime.strptime() to parse the inDate string into a date object, use datetime.strftime() to output in whatever format you like:

>>> from datetime import datetime
>>> inDate = "29-Apr-2013-15:59:02"
>>> d = datetime.strptime(inDate, "%d-%b-%Y-%H:%M:%S")
>>> d
datetime.datetime(2013, 4, 29, 15, 59, 2)
>>> d.strftime("YYYYMMDD HH:mm:ss (%Y%m%d %H:%M:%S)")
'YYYYMMDD HH:mm:ss (20130429 15:59:02)'
Bryan
  • 14,775
  • 6
  • 46
  • 75
1

Have you investigated dateutil?

http://labix.org/python-dateutil

I found a similar question to yours: How do I translate a ISO 8601 datetime string into a Python datetime object?

Community
  • 1
  • 1
David
  • 145
  • 8
-2

You want to look into datetime, in particular strptime.

Dave
  • 6,236
  • 5
  • 32
  • 65