1
votes

Should be quick, but I can't for the life of me figure this one out.

I'm given the following strings:

  • 201408110000
  • 201408120001
  • 201408130002

Which I loaded as a date(?) time object via the following:

dt = time.strptime(datestring, '%Y%m%d%H%M%S')

Where datestring is the string.

From there, how do I output the following:

  • 11-Aug-14
  • 12-Aug-14
  • 13-Aug-14

I tried str(dt) but all it gave me was this weird thing:

time.struct_time(tm_year=2014, tm_mon=8, tm_mday=11, tm_hour=12, tm_min=1, tm_sec=5, tm_wday=0, tm_yday=223, tm_isdst=-1)

What am I doing wrong? Anything I add so far to dt gives me attribute does not exist or something.

4
Have you tried strftime?Kevin
Yes, but I'm probably not doing it right. I keep getting attribute does not exist.zack_falcon

4 Answers

2
votes

Using strftime

>> dt = time.strftime('%d-%b-%Y', dt)
>> print dt
11-Aug-2014
2
votes

When you use time module it return a time struct type. Using datetime returns a datetime type.

from datetime import datetime

datestring = '201408110000'

dt = datetime.strptime(datestring, '%Y%m%d%H%M%S')

print dt
2014-08-11 00:00:00

print dt.strftime("%d-%b-%Y")
11-Aug-2014

print dt.strftime("%d-%b-%y")
11-Aug-14
0
votes
from datetime import datetime
datestring = "201408110000"
print datetime.strptime(datestring, '%Y%m%d%H%M%S').strftime("%d-%b-%Y")
11-Aug-2014
0
votes

If you're doing a lot of parsing of variety of input time formats, consider also installing and using the dateutil package. The parser module will eat a variety of time formats without specification, such as this concise "one-liner":

from dateutil import parser
datestring = '201408110000'
print parser.parse(datestring).strftime("%d-%b-%Y")

This uses parser to eat the datestring into a datetime, which is then reformatted using datetime.strftime(), not to be confused with time.strftime(), used in a different answer.

See more at https://pypi.python.org/pypi/python-dateutil or the tag.