Using timezone with openpyxl - python-3.x

I need to add a date in an excel file.
I use timezones on these dates. It works very well with django rest framework. (My GET requests return the date with this format: 2022-07-23T13:19:59+02:00) Same in Django admin, the Europe/Paris timezone is well taken into account (+02:00).
However, when I use openpyxl, the indicated time is 2h late (it takes the UTC timezone).
sheet.append([date_recorded.strftime("%d/%m/%Y %H:%M:%S")])
Same thing if I print this date in console. (2022-07-11 15:19:50+00:00)
How to correct this?

You can simply convert it to your desired zone like this:
from dateutil import tz
utctime = "YOUR CURRENT VALUE OF DATETIME"
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("yourzone")
utctime = utctime.replace(tzinfo=from_zone)
new_time = utctime.astimezone(to_zone)

Since you are using django, you can use built-in get_current_timezone to convert datetime objects to the local timezone:
from django.utils import get_current_timezone
timezone = get_current_timezone()
date_recorded = date_recorded.astimezone(timezone)
sheet.append([date_recorded.strftime("%d/%m/%Y %H:%M:%S")])

Related

Dynamically formatting dates and times fetched from an API in iso format

I am fetching data from an API that comes in iso formated strings, for ex - example 2022-07-27T00:00:00.0000000+01:00
end_date=item['RunDate']
start_time=portion['StartTimeWTT']
I am trying to format the date to look like: yyyy-mm-dd and time hh:mm:ss
I have tried different solutions but none of them works
end_date1=item['RunDate']
end_date=datetime.date().strftime(end_date1,'%Y-%M-%d')
or datetime.fromisoformat
I would be grateful for any suggestions.
For me, the easiest way to handle date strings is by using the dateutil library. For example in your cited case:
from dateutil import parser
from dateutil.utils import default_tzinfo
from dateutil.tz import tzoffset
tx = '2022-07-27T00:00:00.0000000+01:00'
tz_data = tzoffset("EST", 0)
print(default_tzinfo(parser.parse(tx) , tz_data))
yields
2022-07-27 00:00:00+01:00

What's a good way of converting timezone of a timestamp?

I have a string in this format: 09/20/2020 10:30 AM
That timestamp is in Eastern Timezone.
I need to obtain the UTC equivalent, but in the following ISO format: 2020-09-20T14:30:00.0000Z
I've tried a few things but there doesn't seem to be a clean/short way of converting it.
So far I've tried:
dtSept = "09/20/2020 10:00 PM"
dtSeptTZ = pytz.timezone('US/Eastern').localize(datetime.datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")).isoformat(timespec='milliseconds')
dtSeptTZ at this point is a string object.
If I have to convert its TimeZone and format it, I have to execute the following which each take a datetime object but return a string.
dtSeptTZ.astimezone(pytz.timezone('Etc/UTC'))
dtSeptTZ.strftime("%Y-%m-%dT%I:%M.%fZ")
Is there a clean/short way of getting the proper output without coverting it back and forth between string and datetime?
Many thanks.
due to the immanent deprecation of pytz, I'd suggest to use dateutil. The usage of dateutil also transforms nicely to Python 3.9's zoneinfo.
from datetime import datetime, timezone
from dateutil.tz import gettz
dtSept = "09/20/2020 10:00 PM"
# string to datetime object
dt = datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")
# set tzinfo to appropriate time zone; (!) use "localize" instead with pytz timezone class
dt = dt.replace(tzinfo=gettz('US/Eastern'))
# to UTC (could use any other tz here)
dt_utc = dt.astimezone(timezone.utc)
# to ISO format string:
print(dt_utc.isoformat())
>>> 2020-09-21T02:00:00+00:00

Python Time zone: get abbreviation and UTC offset

my time zone is "Australia/Melbourne" (I have multiple zones like this when I give this to my function) and I need the output like this ASET(GMT +10). How can I reach my answer?
Thank you
assuming you have date and time available (see my comment), the easiest way is probably strftime:
from datetime import datetime
from dateutil import tz
timezone = tz.gettz("Australia/Melbourne")
dt = datetime.now(timezone)
print(f"{dt.strftime('%Z')}(GMT{dt.strftime('%z')})")
# AEST(GMT+1000)
If you exactly want to get the specified output, I suppose you have to go a little more sophisticated:
total_minutes, seconds = divmod(dt.utcoffset().total_seconds(), 60)
hours, minutes = divmod(total_minutes, 60)
utcoff = f"{int(hours):+d}:{int(minutes):02d}" if minutes else f"{int(hours):+d}"
print(f"{dt.strftime('%Z')}(GMT{utcoff})")
# AEST(GMT+10)

Today's date without time aspect

I am currently trying to achieve an output which gives today's date without time.
I currently have the code
import datetime as date
today = date.datetime.today().strftime("%Y-%m-5%d")
You can simply do this:
from time import strftime
print(strftime('%b %d, %Y')) #or use '%Y-%m-%d'

Time data from API convert to Date time python

i have this problem with milliseconds or microseconds data from api im not totally sure. I am trying to convert this to a readable date time. below is an example. The web app has a dashboard which you i can check the date time. but i do not know exactly how to convert it to a readable date time.
Example 1:
FROM API
"start":1542243678,
FROM Dashboard
11/15/2018 9:01 am
Example 2:
FROM API
"end":1542330078,
FROM Dashboard
11/16/2018 9:01 am
When i try to convert to python date time it gives me wrong info.
import datetime
import time
milliseconds = 1542243678
date = datetime.datetime.fromtimestamp(milliseconds/1000.0)
date = date.strftime('%Y-%m-%d %H:%M:%S')
print(date)
Output:
1970-01-19 04:24:03
Sorry if I don't understand your question correctly, but is this what you want?
import datetime
import time
milliseconds = 1542243678
date = datetime.datetime.fromtimestamp(milliseconds)
date = date.strftime('%m/%d/%Y %I:%M %p')
print(date)
Output: 11/14/2018 05:01 PM
You don't need to divide by 1000 before passing to datetime.datetime.fromtimestamp.
Try datetime.datetime.fromtimestamp(1542243678). It should work.

Resources