Parsing Dates with -0400 Timezone String in Python
Parsing dates with trailing timezone specifications can be tricky in Python, especially when the conventional %z format tag is unavailable. In Python 2.6.x and higher, the %z format tag has been removed, leaving developers with the challenge of handling such string formats correctly.
Solution
To parse date strings with -0400 timezones in Python, you can utilize the parse function from the dateutil library:
from dateutil.parser import parse date_string = '2009/05/13 19:19:30 -0400' date_object = parse(date_string) print(date_object)
Output:
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))
The date_object obtained is a datetime object with timezone information. Note that the timezone offset is represented as -14400 seconds, which corresponds to -0400 timezone.
Alternatives
For Python 3.0 and above, dateutil2.0 is recommended for date parsing. However, for Python 2.x, dateutil1.5 should be used instead.
The above is the detailed content of How to Parse Dates with -0400 Timezone String in Python?. For more information, please follow other related articles on the PHP Chinese website!