4

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"

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
    import datetime
    date = datetime.datetime.utcnow().strftime("%c")
    print date # >>> 'Tue Sep  8 10:14:17 2015'`

1 Comment

please add some explanation to your answer so that others will get it quickly and correctly.
0

Try this..

from datetime import datetime
date = datetime.utcnow().ctime()
print date # >>> 'Tue Sep  8 10:10:22 2015'

1 Comment

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.

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.