python converting any datetime string to UTC [duplicate] - python

This question already has answers here:
Parsing date/time string with timezone abbreviated name in Python?
(6 answers)
Convert UTC datetime string to local datetime
(16 answers)
Closed 6 years ago.
I have a tedious function that does something like this:
...
if ('PDT' in stringVal) or ('PST' in stringVal):
utcdateTime = convert(stringVal)+(hardcode the offset)
elif('EDT' in stringVal)...
...
I looked at several posts including this but couldn't find anything that fits my purpose. I also looked at datetime.datetime and the whole datetime module in general but it has things like .now(); .utcnow(); datetime.now(tz.pytz.utc) etc etc. Basically if I have something like:
2014-05-01 01:02:03 PDT
2014-05-01 01:02:03 PST
2014-05-01 01:02:03 EDT
2014-05-01 01:02:03 EST
2014-05-01 01:02:03 MDT
2014-05-01 01:02:03 MST
Is there a python module that has some method I can use to convert those above datetime strings to UTC? If there is none, I will just stick with the hard-coded way I have.

You'll need to translate the timezone strings, but otherwise you can use the datetime and pytz libraries.
import datetime
import pytz
s = '2014-05-01 01:02:03 PST'
ds, tzs = s.rsplit(' ', 1)
tz_map = {
'PST': 'US/Pacific',
'EST': 'US/Eastern'
}
tz = pytz.timezone(tz_map[tzs])
dt = datetime.datetime.strptime(ds, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tz)
dt_utc = dt.astimezone(pytz.utc)

Related

How to convert datetime.date to PST timezone? [duplicate]

This question already has answers here:
Display the time in a different time zone
(12 answers)
Convert UTC datetime string to local datetime
(16 answers)
Closed 5 months ago.
Date = dt.datetime.today().date()
I have a date here but it's in UTC, for example at PST 2022-09-18 5PM it will turn into 2022-09-19, but I want to convert it into PST time.
You need to use a timezone aware datetime - a naive datetime (like datetime.date) has no timezone information.
So, use a datetime.datetime with a tzinfo, and then you can localize to UTC and convert to Pacific time:
from datetime import datetime
from dateutil import tz
pst = tz.gettz('America/Los_Angeles')
dt = datetime(2016, 1, 1, tzinfo=tz.UTC)
pst_dt = dt.astimezone(pst)
This gives you a datetime representing 2016-01-01 00:00:00 in the Pacific timezone.
You can of course start out with a naive datetime and use replace to add a UTC timezone:
dt = datetime(2016, 1, 1).replace(tzinfo=tz.UTC)

How do I convert a LabVIEW decimal date into a string datetime format using Python?

I need to convert a decimal timestamp in a JSON file generated using LabVIEW into a string datetime so that I can POST it to an API I'm using. For instance, one such decimal timestamp is 3640111724.4817362; how can I do this?
EDIT: This article from NI describes how they format their timestamps. They're starting from a nonstandard epoch (01/01/1904 00:00:00.00 UTC), so in other words, Python's interpretation is 66 years ahead.
just use datetime.fromtimestamp from datetime and format It with strftime as you want:
EDIT: subtracting 66 years to match with datetime timestamp pattern
from dateutil.relativedelta import relativedelta
from datetime import datetime
timestamp = 3640111724.4817362
date = datetime.fromtimestamp(timestamp)
date = date - relativedelta(years=66)
print(date.strftime("%m/%d/%Y, %H:%M:%S"))
Output:
05/07/2019, 22:08:44
The number of seconds between 1904-01-01 00:00:00 UTC and 1970-01-01 00:00:00 UTC is 2082844800, so you just need to adjust your LabView timestamp before creating your Python datetime object.
from datetime import datetime
timestamp = 3640111724.4817362
dt = datetime.fromtimestamp(timestamp - 2082844800)
print(dt)
# 2019-05-07 22:08:44.481736

Python - Convert ISO 8601 to BST time

So basically I have learned a bit with ISO 8601 where the format is
"2018-07-06T07:00:00.000"
and basically what I have achieved is that I starting of to change the ISO to a more formal timestamp which is:
etatime = str(datetime.datetime.strptime("2018-07-06T07:00:00.000", "%Y-%m-%dT%H:%M:%S.%f"))
which will give an output of:
2018-07-06 07:00:00
However I noticed the time is 1 hour behind the BST (British time) which should be added one hour.
My question is, is there possible to go from (2018-07-06T07:00:00.000) to (2018-07-06 08:00:00 BST)?
Assumptions: the input represents a UTC timestamp, and you want to localise that to London time. You probably do not want to localise it to BST time, since BST is the DST variation of GMT, and an actual location like London will switch between BST and GMT depending on the time of year. You'll want to install the pytz module.
from datetime import datetime, timezone
import pytz
date = '2018-07-06T07:00:00.000'
utc_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
london_date = utc_date.astimezone(pytz.timezone('Europe/London'))
datetime.datetime(2018, 7, 6, 8, 0, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)
strptime gives you a naïve datetime object (without timezone information), .replace gives you an aware datetime object (with timezone information), which then enables you to simply convert that to a different timezone.
One suggestion is that you can use the timedelta function from datetime module:
from datetime import datetime, timedelta
etatime = datetime.strptime("2018-07-06T07:00:00.000", "%Y-%m-%dT%H:%M:%S.%f")
# Before adding one hour
print(etatime)
etatime = etatime + timedelta(hours=1)
# After adding one hour
print(etatime)
Output:
2018-07-06 07:00:00
2018-07-06 08:00:00

How to convert a datetime into timestamp with timezone(Asia/Dubai) included? [duplicate]

This question already has answers here:
python - datetime with timezone to epoch
(3 answers)
Closed 6 years ago.
I am able to convert to date from a timestamp, but the conversion from datetime to timestamp is giving wrong answer. here's my code
import datetime
from pytz import timezone
datetime.datetime.fromtimestamp(1426017600,timezone("Asia/Dubai")).strftime('%Y-%m-%d %H:%M:%S')
output:'2015-03-11 00:00:00'
How to include timezone when converting back to timestamp from datetime ?
>>datetime.datetime(2015,03,11).strftime('%s')
output:1426012200
from datetime import datetime, time, date
from pytz import timezone, utc
tz = timezone("Asia/Dubai")
d = datetime.fromtimestamp(1426017600,tz)
print d
midnight = tz.localize(datetime.combine(date(d.year, d.month, d.day),time(0,0)), is_dst=None)
print int((midnight - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())
Based on code from python - datetime with timezone to epoch

Parse timezone abbreviation to UTC [duplicate]

This question already has answers here:
Parsing date/time string with timezone abbreviated name in Python?
(6 answers)
Closed 8 years ago.
How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch?
Currently my best approach is to use time.strptime() is this:
def to_unixepoch(s):
# ignore the time zone in strptime
a = s.split()
b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z")
# this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME)
c = int(time.mktime(b))
# UTC+TZ
c -= time.timezone
# UTC
c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]]
return c
I see from other questions that it might be possible to use calendar.timegm(), and pytz among others to simplify this, but these don't handle the abbreviated time zones.
I'd like a solution that requires minimal excess libraries, I like to keep to the standard library as much as possible.
The Python standard library does not really implement time zones. You should use python-dateutil. It provides useful extensions to the standard datetime module including a time zones implementation and a parser.
You can convert time zone aware datetime objects to UTC with .astimezone(dateutil.tz.tzutc()). For the current time as a timezone aware datetime object, you can use datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()).
import dateutil.tz
cet = dateutil.tz.gettz('CET')
cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)
cesttime.isoformat()
'2010-04-01T12:57:00+02:00'
cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)
cettime.isoformat()
'2010-01-01T12:57:00+01:00'
# does not automatically parse the time zone portion
dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\
.replace(tzinfo=dateutil.tz.gettz('CET'))
Unfortunately this technique will be wrong during the repeated daylight savings time hour.

Categories