1

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.

2
  • Have you tried strftime? Commented Sep 25, 2014 at 18:59
  • Yes, but I'm probably not doing it right. I keep getting attribute does not exist. Commented Sep 25, 2014 at 19:05

4 Answers 4

2

Using strftime

>> dt = time.strftime('%d-%b-%Y', dt)
>> print dt
11-Aug-2014
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

Is datetime built-in to Python? I just used import time. I recall having to install a plug-in or something on my local computer (can't remember if it's datetime or dateutil or something else), which is something I can't do once I migrate this to a server.
datetime is standard. See list of formatting otions for strftime in the docs.
datetime is builtin. You should have installed dateutil
0
from datetime import datetime
datestring = "201408110000"
print datetime.strptime(datestring, '%Y%m%d%H%M%S').strftime("%d-%b-%Y")
11-Aug-2014

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.