In this article, we will learn how to Convert UTC to CST EST PST in Python. We will make use of the datetime module of Python to get the current date and time. Once we have the current date and time then we will convert it to time zones like CST, EST, and PST of USA time zones. We can convert to any other time zone also, and the methods and code will be similar.
Environment and Requirement:-
- Python Interpreter
- datetime Module
- timezone module
- strftime() function
- astimezone() function
- You will need to install pytz library by using the below command:pip install pytz
How to Convert UTC to CST EST PST in Python
- Import datetime from datetime module.
- Import timezone from pytz library.
- Get input in a specified format.
- Datetime.now() is used to return local date & time defined by the module.
- Then print UTC timezone using utc.strftime().
- Then used now_est as an object which is storing now_utc.astimezone() which manipulates objects of the datetime class.
- Then print EST timezone using now_est.strftime().
- Then used now_pst as an object that stores now_utc.astimezone(‘US/Pacific’) to manipulate objects of datetime class.
- Then print PST timezone using now_pst.strftime().
- Used now_cst as an object which stores now_utc.astimezone(‘US/Central’) to manipulate objects of datetime class.
- Then print CST timezone using now_cst.strftime().
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
now_utc = datetime.now(timezone('UTC'))
print('UTC',now_utc.strftime(format))
now_est=now_utc.astimezone(timezone('EST'))
print('EST',now_est.strftime(format))
now_pst=now_utc.astimezone(timezone('US/Pacific'))
print('PST',now_pst.strftime(format))
now_cst=now_utc.astimezone(timezone('US/Central'))
print('CST',now_cst.strftime(format))
Output:
UTC 2022-12-31 12:33:32 UTC+0000
EST 2022-12-31 07:33:32 EST-0500
PST 2022-12-31 04:33:32 PST-0800
CST 2022-12-31 06:33:32 CST-0600