Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:
datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".
Converting Between TimezonesUse the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.
Getting the UTC timestampdatetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.
The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime. Here range of the utcoffset is “timedelta(hours=24) <= offset <= timedelta(hours=24)”.
You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.
Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.
>>> from dateutil.parser import parse
>>> parse("2009-08-18 13:52:54-04")
datetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))
(is this question a duplicate?)
use Babel, specifically parse_datetime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With