Home >Backend Development >Python Tutorial >How to Parse Dates with Timezone String '-0400' in Python?

How to Parse Dates with Timezone String '-0400' in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 13:42:02976browse

How to Parse Dates with Timezone String '-0400' in Python?

Parsing Dates with Timezone String '-0400' in Python

In Python, parsing dates with the '-0400' timezone string can be a hassle, especially if you're trying to use strptime. However, there's a simple solution using the dateutil library.

Solution Using Dateutil

from dateutil.parser import parse

date_string = '2009/05/13 19:19:30 -0400'
dt = parse(date_string)

print(dt)
# Output: datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

The parse function from dateutil allows you to easily parse a date string and obtain a datetime object with the correct timezone information.

Compatibility with Python Versions

Note that dateutil2.0 is only compatible with Python 3.0 and above. If you're using Python 2.x, you will need to use dateutil1.5 instead.

The above is the detailed content of How to Parse Dates with Timezone String '-0400' in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn