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

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)

Related

Python convert timestamp to unix

I know these questions have been asked before but I'm struggling to convert a timestamp string to a unix time and figuring out whether the datetime objects are naive or aware
For example, to convert the time "2021-05-19 12:51:47" to unix:
>>> from datetime import datetime as dt
>>> dt_obj = dt.strptime("2021-05-19 12:51:47", "%Y-%m-%d %H:%M:%S")
>>> dt_obj
datetime.datetime(2021, 5, 19, 12, 51, 47)
is dt_obj naive or aware and how would you determine this? The methods on dt_obj such as timetz, tzinfo, and tzname don't seem to indicate anything - does that mean that dt_obj is naive?
Then to get unix:
>>> dt_obj.timestamp()
1621421507.0
However when I check 1621421507.0 on say https://www.unixtimestamp.com then it tells me that gmt for the above is Wed May 19 2021 10:51:47 GMT+0000, ie 2 hours behind the original timestamp?
since Python's datetime treats naive datetime as local time by default, you need to set the time zone (tzinfo attribute):
from datetime import datetime, timezone
# assuming "2021-05-19 12:51:47" represents UTC:
dt_obj = datetime.fromisoformat("2021-05-19 12:51:47").replace(tzinfo=timezone.utc)
Or, as #Wolf suggested, instead of setting the tzinfo attribute explicitly, you can also modify the input string by adding "+00:00" which is parsed to UTC;
dt_obj = datetime.fromisoformat("2021-05-19 12:51:47" + "+00:00")
In any case, the result
dt_obj.timestamp()
# 1621428707.0
now converts as expected on https://www.unixtimestamp.com/:
As long as you don't specify the timezone when calling strptime, you will produce naive datetime objects. You may pass time zone information via %z format specifier and +00:00 added to the textual date-time representation to get a timezone aware datetime object:
from datetime import datetime
dt_str = "2021-05-19 12:51:47"
print(dt_str)
dt_obj = datetime.strptime(dt_str+"+00:00", "%Y-%m-%d %H:%M:%S%z")
print(dt_obj)
print(dt_obj.timestamp())
The of above script is this:
2021-05-19 12:51:47
2021-05-19 12:51:47+00:00
1621428707.0
datetime.timestamp()
Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion.
So using this does automatically apply yours machine current timezone, following recipe is given to calculate timestamp from naive datetime without influence of timezone:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

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

python converting any datetime string to UTC [duplicate]

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)

Categories