[파이썬] 날짜와 시간의 시간대 이동

Python provides a built-in module called datetime that allows us to manipulate dates and times. In addition to performing basic operations such as adding or subtracting days, it also allows for performing time zone conversions.

Setting the Time Zone

To work with time zones in Python, we need to use the pytz library. This library provides a comprehensive database of time zones and helps in handling time zone conversions.

To get started, we need to install pytz using pip:

pip install pytz

Once pytz is installed, we can import it in our Python script:

import pytz

Converting time zones

Let’s say we have a datetime object representing a specific date and time in a certain time zone, and we want to convert it to another time zone.

Here’s some sample code that demonstrates how to do this:

import pytz
from datetime import datetime

# Create a datetime object in the original time zone
original_time = datetime(2022, 1, 1, 12, 0, tzinfo=pytz.timezone('US/Eastern'))

# Convert to a different time zone
new_time = original_time.astimezone(pytz.timezone('Asia/Tokyo'))

# Print the original and converted times
print(f"Original time: {original_time}")
print(f"Converted time: {new_time}")

In this example, we create a datetime object original_time with a given time zone (US Eastern). We then use the astimezone() method to convert it to a different time zone (Asia/Tokyo).

Finally, we print the original and converted times to verify the change in time zone.

Working with UTC

UTC (Coordinated Universal Time) is a common reference time used by different time zones. Python provides good support for working with UTC.

Here’s an example that demonstrates how to work with UTC in Python:

from datetime import datetime
import pytz

# Get the current UTC time
current_time = datetime.now(pytz.timezone('UTC'))

# Print the current UTC time
print(f"Current UTC time: {current_time}")

# Convert the UTC time to a specific time zone
local_time = current_time.astimezone(pytz.timezone('US/Central'))

# Print the converted local time
print(f"Converted local time: {local_time}")

In this code snippet, we first get the current UTC time using the datetime.now() method with the UTC time zone. We then use the astimezone() method to convert the UTC time to a specific time zone (US/Central in this case).

Finally, we print the current UTC time and the converted local time to demonstrate the conversion.

Conclusion

In Python, manipulating dates and times, including time zone conversions, is made easy using the datetime and pytz modules. By following the examples provided in this blog post, you should now have a good understanding of how to perform time zone conversions in Python.