1

I have a script that has been written that I need to change the date on, when the script runs it outputs this message

output_messaging("*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON " + 
    str(datetime.date.today().day) + "/" + str(datetime.date.today().month) + "/" +            
    str(datetime.date.today().year) + " AT " + str(datetime.datetime.now().hour) + ':' +   
    str(datetime.datetime.now().minute) + ':' + str(datetime.datetime.now().second) + " ***\n\n")

Which gives

*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 20/2/2012 AT 18:3 ***

I need the date converted to

20/Feb/2012 , how do i do this?

rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
MapMan
  • 630
  • 2
  • 13
  • 28
  • 1
    Use time.strftime for date formatting. [See this post.][1] [1]: http://stackoverflow.com/questions/4855406/how-to-convert-a-time-to-a-string – Art Swri Feb 28 '12 at 16:37

4 Answers4

2
output_messaging("*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON {0:%d/%b/%Y} AT {0:%H:%M} ***".format(datetime.datetime.now()))

prints

*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/2012 AT 17:41 ***

More information about datetime formatting

eumiro
  • 207,213
  • 34
  • 299
  • 261
2

Use strftime for this -- it's way easier than doing a bunch of custom concatenation. There's a table of formatting conventions here.

>>> s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
...     "%d/%b/%y AT %H:%M:%S ***\n\n"
>>> datetime.datetime.now().strftime(s)
'*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 11:44:03 ***\n\n'

As eumiro's answer indicates, you can also invert the above call with a slightly modified format string like so:

>>> s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
...     "{0:%d/%b/%y} AT {0:%H:%M:%S} ***\n\n"
>>> s.format(datetime.datetime.now())
'*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 13:41:10 ***\n\n'

This works because format simply calls the (shockingly under-documented) __format__ method of the datetime.datetime object. For example:

>>> datetime.datetime.now().__format__('The current month is %B')
'The current month is February'

This works for other types too:

>>> (16).__format__('x')
'10'

For more on __format__, see PEP 3101

Community
  • 1
  • 1
senderle
  • 145,869
  • 36
  • 209
  • 233
  • Looks like a correct solution so +1 from me. If you suspect someone has been voting inappropriately you can flag it for moderator attention. – Mark Ransom Feb 28 '12 at 17:01
  • @MarkRansom, for what it's worth, I also wondered how eumiro's approach worked. The above is what I figured out with some sleuthing. But I'm surprised at how poorly-documented this part of Python is. – senderle Feb 28 '12 at 18:50
1
>>> from datetime import date
>>> day = date.today()
>>> day.strftime('%d/%b/%y')
'28/Feb/12'
Fred
  • 1,011
  • 1
  • 10
  • 36
0
import datetime
print datetime.datetime.now().strftime('%d/%b/%Y')
# 28/Feb/2012
Dzinx
  • 55,586
  • 10
  • 60
  • 78