How could I get the local time, like right now its 9:06 For my friends, Its 6:06. How could I get that time In python. I have tried using DateTime but have had no luck finding a way to do this.
-
Does this answer your question? [How can I convert from UTC time to local time in python?](https://stackoverflow.com/questions/68664644/how-can-i-convert-from-utc-time-to-local-time-in-python) – jezza_99 Jan 17 '22 at 00:13
-
Welcome back to Stack Overflow. " I have tried using DateTime but have had no luck finding a way to do this." Did you try putting `python datetime local time` [into a search engine](https://duckduckgo.com/?q=python+datetime+local+time)? Since you want the current time, how about if you [add `current` to that](https://duckduckgo.com/?q=python+datetime+current+local+time)? When you looked at those search results, what code did you try writing? What went wrong with it? – Karl Knechtel Jan 17 '22 at 00:14
5 Answers
You can use pytz library.
from datetime import datetime
import pytz
datetime_NewYork = datetime.now(pytz.timezone('America/New_York'))
print("NY time:", datetime_NewYork.strftime("%H:%M:%S"))
datetime_London = datetime.now(pytz.timezone('Europe/London'))
print("London time:", datetime_London.strftime("%H:%M:%S"))

- 464
- 2
- 16
You can use time library, and localtime()/asctime() function.
import time
# This will give you o/p in the format of
# time.struct_time(tm_year=2022, tm_mon=1, tm_mday=16, tm_hour=19, tm_min=14, tm_sec=39, tm_wday=6, tm_yday=16, tm_isdst=0)
print(time.localtime())
# This will give you o/p in more simpler manner
# 'Sun Jan 16 19:15:01 2022'
print(time.asctime())
You can also use time.time(), but you have to do conversion afterwards.

- 55
- 1
- 9
According to python docs both methods of the datetime module:
import datetime
print(datetime.datetime.today()) # method 1
print(datetime.datetime.now()) # method 2
return the local time (time according to your current time on the machine you are running this code)
The 1st method uses only local time. The 2nd method gives you the ability to pass the optional argument tz
which allows you to specify the timezone. But in order to do so, you will need to install a timezone library for python and import it into your code. For example - the abovementioned pytz
.
Here is the terminal command for installing pytz library:
sudo -H pip install pytz
Here is an amazing youtube tutorial about the datetime module: https://www.youtube.com/watch?v=eirjjyP2qcQ&t=855s
Here is the python docs page dedicated to the datetime module: https://docs.python.org/3/library/datetime.html

- 2,425
- 2
- 8
- 23

- 21
- 3
May be this could help.
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

- 1
- 2