-2

I am using an API, and the API needs this data format:

Wed Jan 07 2015 18:58:40

How I can convert the time now to this data format, using the datetime and time modules?

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
MarcoBuster
  • 1,145
  • 1
  • 13
  • 21
  • @Selcuk I need this data format: Wed Jan 07 2015 18:58:40 – MarcoBuster Mar 24 '16 at 10:06
  • @Selcuk 's comment helps you. Look at the answer to the question Selcuk mentioned, specifically the part where the method **`strftime()`** is explained. This is exactly what you need. – YinglaiYang Mar 24 '16 at 10:13

1 Answers1

4
print(datetime.now().strftime('%a %b %d %Y %H:%M:%S'))

Would display something like:

Thu Mar 24 2016 10:09:18

The formatting options used are as follows:

  • %a Weekday as locale’s abbreviated name.
  • %b Month as locale’s abbreviated name.
  • %d Day of the month as a zero-padded decimal number.
  • %Y Year with century as a decimal number.
  • %H Hour (24-hour clock) as a zero-padded decimal number.
  • %M Minute as a zero-padded decimal number.
  • %S Second as a zero-padded decimal number.

To then convert this to a format for sending, you probably want to investigate quote_plus(), for example:

from datetime import datetime
import urllib

now = datetime.now().strftime('%a %b %d %Y %H:%M:%S')
print(urllib.parse.quote_plus(now))

This would give you:

Thu+Mar+24+2016+10%3A32%3A51
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • For additional information on formatting options, check [the docs](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior). – jbndlr Mar 24 '16 at 10:10
  • 1) Thanks for the answer 2) But If I need "Thu%20Mar%2024%202016%2010:09:18" How I can do it? – MarcoBuster Mar 24 '16 at 10:27
  • If you are trying to encode it, then more than just the spaces should be escaped. You can make use of the `quote_plus()` function. I have added an example. – Martin Evans Mar 24 '16 at 10:38