3

How I can get on python result as new Date().toUTCString() on Javascript?

on Javascript I make:

new Date().toUTCString()
"Tue, 08 Sep 2015 09:45:32 GMT"

on Python

import datetime # or time, or either
date = ??? # some code
print date # >>> "Tue, 08 Sep 2015 09:45:32 GMT"
Yuriy Leonov
  • 536
  • 1
  • 9
  • 33

3 Answers3

6

The time format looks similar to RFC 2822 format (used in emails):

>>> import email.utils
>>> email.utils.formatdate(usegmt=True)
'Tue, 08 Sep 2015 10:06:04 GMT'

Or you can get any time format you want using datetime.strftime():

>>> from datetime import datetime, timezone
>>> d = datetime.now(timezone.utc)
>>> d
datetime.datetime(2015, 9, 8, 10, 6, 4, tzinfo=datetime.timezone.utc)
>>> str(d)
'2015-09-08 10:06:04+00:00'
>>> d.strftime('%a, %d %b %Y %H:%M:%S %Z')
'Tue, 08 Sep 2015 10:06:04 UTC'
>>> d.strftime('%a, %d %b %Y %H:%M:%S %z')
'Tue, 08 Sep 2015 10:06:04 +0000'

where timezone.utc is defined here.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
1
    import datetime
    date = datetime.datetime.utcnow().strftime("%c")
    print date # >>> 'Tue Sep  8 10:14:17 2015'`
zabusa
  • 2,520
  • 21
  • 25
0

Try this..

from datetime import datetime
date = datetime.utcnow().ctime()
print date # >>> 'Tue Sep  8 10:10:22 2015'
MarmiK
  • 5,639
  • 6
  • 40
  • 49
avichalp
  • 1,100
  • 11
  • 11
  • Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Sep 08 '15 at 11:21