1

So the default time for Python is London, but I am trying to change it to EDT/New York time. This is what I did:

import datetime

time = datetime.datetime.now()
print('{}:{}'.format(time.strftime('%I'), time.strftime('%M')))

I want to make it EDT time, so I looked up ways to do it, but every time i got something different and it wouldn't work. I am very confused.

P.S I'm using onlineGDB as a compiler, so some things don't work.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    Does this answer your question? [How to convert local time string to UTC?](https://stackoverflow.com/questions/79797/how-to-convert-local-time-string-to-utc) – Tomerikoo Sep 27 '20 at 15:04
  • 1
    "*the default time for Python is London*" - that is incorrect; by default, Python will use the local time your OS is configured to use. – FObersteiner Sep 28 '20 at 06:54
  • @Tomerikoo: the linked dupe for me seems to be confusing to newcomers (and outdated in some places); + the OP just wanted to get time in a specific time zone, not UTC. – FObersteiner Sep 28 '20 at 07:33

2 Answers2

0

Have you tried pytz?

from pytz import timezone
EDT = timezone('America/New_York')
time = EDT.localize(datetime.datetime.now())

print('{}:{}'.format(time.strftime('%I'), time.strftime('%M')))
Omri
  • 483
  • 4
  • 12
  • I have tried some variations of it. Also, the code you wrote still displays the London time. It may just be GitHub, or maybe I'm just using it wrong. I haven't been coding for too long, maybe around a couple months. –  Sep 25 '20 at 18:56
  • 1
    please note the [pytz deprecation](https://pypi.org/project/pytz-deprecation-shim/). for now, there's `dateutil`; until in Python 3.9 you'll have `zoneinfo`. – FObersteiner Sep 28 '20 at 06:58
0

the now classmethod has a tz argument which you should use to set the appropriate timezone; e.g.

from datetime import datetime
from dateutil.tz import gettz

print(datetime.now(gettz('America/New_York')))
>>> 2020-09-28 02:56:19.063552-04:00

This code also works fine if you use the gdb online Python debugger.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Thank you, it works. Is it possible to assign the datetime.now(gettz('America/New_York')) to a variable, then get the time in 12-hour clock? That is what I was initially trying to do. –  Sep 30 '20 at 15:48
  • OK I played with it a little bit, and it works. Thank you! –  Sep 30 '20 at 15:51