timedelta to 12 pm CET - python

I am trying to get the remaining time to 12 pm Europe/Berlin on a machine with unknown local timezone (GitHub actions).
I have a function that should return a timedelta, with the remaining time until 12 pm.
import datetime
import pytz
def get_twelve_pm():
cest = pytz.timezone('Europe/Berlin')
now = datetime.datetime.now(tz=cest)
twelve_pm = datetime.datetime(
now.year, now.month, now.day, 12).astimezone(cest)
print(cest)
print(now)
print(twelve_pm)
print(twelve_pm - now)
for some reason, in GitHub actions, the result is:
Europe/Berlin
2020-12-10 12:15:46.446839+01:00
2020-12-10 13:00:00+01:00
0:44:13.553161
Why does it say 13:00+01:00? I want it to say 12:00+01:00 as the function says?

you can replace the attributes of your aware datetime object now as desired, e.g.
import datetime
import pytz
tz_Berlin = pytz.timezone('Europe/Berlin')
now = datetime.datetime.now(tz=tz_Berlin)
twelve_pm = now.replace(hour=12, minute=0, second=0, microsecond=0)
# datetime.datetime(2020, 12, 10, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
or create a datetime object representing 12 pm on the same date with localize (the correct way with pytz):
twelve_pm = tz_Berlin.localize(datetime.datetime(now.year, now.month, now.day, 12))
# datetime.datetime(2020, 12, 10, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
...or use Python 3.9's zoneinfo so you can directly set the tzinfo:
from zoneinfo import ZoneInfo
tz_Berlin = ZoneInfo('Europe/Berlin')
twelve_pm = datetime.datetime(now.year, now.month, now.day, 12, tzinfo=tz_Berlin)
# datetime.datetime(2020, 12, 10, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Related

Format date in datetime

i have a date which returns in format of datetime.datetime(2022, 8, 29, 0, 3, 17, 37389)
i want it to be formatted to datetime.datetime(2022, 8, 29, 0, 0).
def some_method_to_return()
due_date = timezone.datetime.strptime(
Aug 29, 2022, '%B %d, %Y'
)
return due_date
due_date = datetime.datetime(2022, 8, 29, 0, 0)
the need to check todays date with due_date if its true how can format today's date in due_date form
from datetime import datetime
def keepJustTheDate(d:datetime):
return d.replace(hour=0, minute=0, second=0, microsecond=0)
Just look into the datetime docs
https://docs.python.org/3/library/datetime.html#datetime.date.replace
I'm not sure if this is what you need, but it might work.
due_date = datetime.datetime(2022, 8, 29, 0, 0)
today = datetime.datetime.now()
def is_today():
if due_date.date() == today.date():
return today.replace(hour = 0, minute=0, second=0, microsecond=0)
else:
return "Not today"
>>> from datetime import datetime
>>> now = datetime.now()
>>> now_string = now.strftime('%Y %m %d %H %M')
>>> now = datetime.strptime(now_string, "%Y %m %d %H %M")
>>> now
datetime.datetime(2022, 8, 29, 13, 21)
You basically have to convert it to a string first using the strftime function. Then using strptime you can convert it back to a datetime object.

how to convert datetime object python to current?

I have the following datetime, and I converted to datetime object.
How do I convert it to say GMT+7 timezone?
date = "2020-07-27T16:38:20Z"
curr = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
print(curr)
If converting to a timezone will work for you then you can convert it like this:
import datetime as dt
from pytz import timezone
date = "2020-07-27T16:38:20Z"
curr = (
dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
.astimezone(timezone('US/Pacific'))
)
print(curr)
OUTPUT:
2020-07-27 09:38:20-07:00
You can list the available timezones like this:
from pytz import all_timezones
for tz in all_timezones:
print(tz)
You can use this code here:
import pytz
date = datetime(2020, 7, 27, 16, 38, 20)
local_time_zone = pytz.timezone('GMT+0')
Or you can get your local time zone
# from tzlocal import get_localzone
# local_time_zone = get_localzone()
def utc_to_local(date):
local_date = date.replace(tzinfo=pytz.utc).astimezone(local_time_zone)
return local_time_zone.normalize(local_date)
print(utc_to_local(date).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
print(utc_to_local(datetime.utcnow()).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
The output will be like this:
2020-07-27 16:38:20.000000 GMT+0000
2020-07-28 13:31:23.219703 GMT+0000

python convert PST time to UTC isoformat

ex:
I have a date string
2018-02-17 16:15:36.519 PST
How do i convert into isoformat in UTC like below
2018-02-18T00:15:36.519Z
I tried this
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
print parse(d1)
it prints like this. How do i convert it to UTC with Z at the end.
2018-02-17 16:15:36.519000-08:00
EDIT
using python 2.7.
import dateutil
import pytz
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
d2=dateutil.parser.parse(d1)
d2.replace(tzinfo=pytz.utc) - d2.utcoffset()
d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat()
print d3
then formatting with Z as suggested
To parse a time string with a timezone abbreviation (PST) into a timezone-aware datetime object:
import dateparser # pip install dateparser
pst_dt = dateparser.parse('2018-02-17 16:15:36.519 PST')
# -> datetime.datetime(2018, 2, 17, 16, 15, 36, 519000, tzinfo=<StaticTzInfo 'PST'>)
To convert the time to UTC timezone:
import datetime as DT
utc_dt = pst_dt.astimezone(DT.timezone.utc)
# -> datetime.datetime(2018, 2, 18, 0, 15, 36, 519000, tzinfo=datetime.timezone.utc)
To print it in the desired format:
print(utc_dt.isoformat()) # -> 2018-02-18T00:15:36.519000+00:00
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # -> 2018-02-18T00:15:36.519000Z
On Python 2.7 there is no DT.timezone.utc:
utc_naive = psd_dt.replace(tzinfo=None) - psd_dt.utcoffset()
print utc_naive.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# -> 2018-02-18T00:15:36.519000Z
Note: in the general case the timezone abbreviation (such as PST) may be ambiguous. See Parsing date/time string with timezone abbreviated name in Python?
In your specific case, the time string corresponds to unique UTC time:
>>> from collections import defaultdict
>>> import datetime as DT
>>> import pytz
>>> naive_dt, tzabbr = DT.datetime(2018, 2, 17, 16, 15, 36, 519000), 'PST'
>>> utc_times = defaultdict(list)
>>> for zone in pytz.all_timezones:
... dt = pytz.timezone(zone).localize(naive_dt, is_dst=None)
... if dt.tzname() == tzabbr: # same timezone abbreviation
... utc_times[dt.astimezone(pytz.utc)].append(zone)
>>> for utc_dt, timezones in utc_times.items():
... print(f'{utc_dt:%c %Z}', *timezones, sep='\n\t')
Sun Feb 18 00:15:36 2018 UTC
America/Dawson
America/Ensenada
America/Los_Angeles
America/Santa_Isabel
America/Tijuana
America/Vancouver
America/Whitehorse
Canada/Pacific
Canada/Yukon
Mexico/BajaNorte
PST8PDT
US/Pacific
US/Pacific-New
See linux convert time(for different timezones) to UTC
This is a demo code from python2.7, FYI, thanks!
from datetime import datetime
from pytz import utc, timezone
def get_current_pst_time():
print('------------(1) Current time to PST time----------------')
local_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
utc_time = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S')
pst_time = datetime.now(tz=utc).astimezone(timezone('US/Pacific')).strftime('%Y-%m-%d %H:%M:%S')
is_summary_time = bool(datetime.now(tz=utc).astimezone(timezone('US/Pacific')).dst())
print('is it a summary time? %s.' % is_summary_time)
print('local time is %s.' % local_time)
print('utc time is %s.' % utc_time)
print('pst time is %s.' % pst_time)
def convert_pst_time_to_utc_time(pst_time_str):
print('------------(2) PST time to UTC time----------------')
print('pst time is %s.' % pst_time_str)
temp_time = datetime.strptime(pst_time_str, '%Y-%m-%d %H:%M:%S')
pacific_timezone = timezone('US/Pacific')
pst_time = pacific_timezone.localize(temp_time, is_dst=None)
assert pst_time.tzinfo is not None
assert pst_time.tzinfo.utcoffset(pst_time) is not None
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
utc_time = pst_time.astimezone(timezone('utc'))
print('utc time is %s.' % utc_time.strftime('%Y-%m-%d %H:%M:%S'))
def convert_utc_time_to_pst_time(utc_time_str):
print('------------(3) UTC time to PST time----------------')
print('utc time is %s.' % utc_time_str)
temp_time = datetime.strptime(utc_time_str, '%Y-%m-%d %H:%M:%S')
utc_timezone = timezone('utc')
utc_time = utc_timezone.localize(temp_time, is_dst=None)
assert utc_time.tzinfo is not None
assert utc_time.tzinfo.utcoffset(utc_time) is not None
pst_time = utc_time.astimezone(timezone('US/Pacific'))
is_summary_time = bool(pst_time.dst())
print('is it a summary time? %s.' % is_summary_time)
print('pst time is %s.' % pst_time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == '__main__':
get_current_pst_time()
convert_pst_time_to_utc_time('2019-12-03 02:00:00')
convert_pst_time_to_utc_time('2020-07-03 02:00:00')
convert_utc_time_to_pst_time('2019-12-03 10:00:00')
convert_utc_time_to_pst_time('2020-07-03 09:00:00')

getting incorrect utc to local time for timezone given

If I run this url : https://api.sunrise-sunset.org/json?lat=12.98&lng=77.61&date=2017-08-26
I get sunrise time: "12:38:14 AM"
and this is UTC time, if I convert it to given timezone using :
from datetime import datetime
import pytz
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = _tz.gettz('UTC')
utc = _datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
but this returns 18:08:16 which is evening time , so what am I doing wrong here.
given timzone is Asia/Kolkata
Example:
>>> from datetime import datetime
>>> from dateutil import tz
>>> from_zone = tz.gettz('UTC')
>>> to_zone = tz.gettz('Asia/Kolkata')
>>> utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
>>> utcTime = "12:38:16" ## from json URL we get AM/PM but I remove it.
>>> utc = datetime.strptime('2017-08-26 {}'.format(utcTime), '%Y-%m-%d %H:%M:%S')
>>> utc
datetime.datetime(2017, 8, 26, 12, 38, 16)
>>> utc = utc.replace(tzinfo=from_zone)
>>> central = utc.astimezone(to_zone)
>>> central
datetime.datetime(2017, 8, 26, 18, 8, 16, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kolkata'))
The problem was that you had "12:38:16 AM" which is actual "00:38:16" so you can't just strip "AM". I changed your function so it will work with "AM" and "PM" hours, just don't strip "AM" and "PM" before using the function:
import pytz
from _datetime import datetime
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = tz.gettz('UTC')
## for formating with AM and PM hours in strptime you need to add
## %p at the end, also instead of %H you need to use %I
utc = datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %I:%M:%S %p')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
date = '2017-08-26'
utcTime = '12:38:14 AM' ## Don't strip AM or PM
timezone = 'Asia/Kolkata'
x = convertUTCtoLocal(date, utcTime, timezone)
print(x)
Also, you can see working example here.

Convert GMT based time to UTC python

I get a date like 2014/08/19 03:38:46 GMT-4 from the database.
How do I convert this into UTC formatted date in Python?
PS: I use Python 2.6.6
Having a non-naive datetime object, you only should invoke astimezone method with desired timezone
>>> import pytz
>>> from dateutil import parser
# dateutil.parser get a datetime object from string, we ensure that is a non-naive datetime
>>> parser.parse('2014/08/19 03:38:46 GMT-4')
datetime.datetime(2014, 8, 19, 3, 38, 46, tzinfo=tzoffset(None, 14400))
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.astimezone (pytz.utc)
datetime.datetime(2014, 8, 18, 23, 38, 46, tzinfo=<UTC>)
You are right in your comment, utc time should go behind, so while I think another solution, what about this
>>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
>>> dt.replace(tzinfo=pytz.utc) + dt.tzinfo._offset
datetime.datetime(2014, 8, 19, 7, 38, 46, tzinfo=<UTC>)
GMT-4 is ambiguous: is it time in America/New_Your (-0400 utc offset) or in Europe/Moscow (+0400)?
$ TZ=GMT-4 date +%Z%z
GMT+0400
$ TZ=UTC-4 date +%Z%z
UTC+0400
$ TZ=America/New_York date +%Z%z
EDT-0400
$ TZ=Europe/Moscow date +%Z%z
MSK+0400
Your comment suggests that you need the sign of the utc offset reversed.
Python 2.6 has no fixed-offset timezones in stdlib. You could use the example implementation from the datetime docs:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class FixedOffset(tzinfo):
"""Fixed UTC offset: `local = utc + offset`."""
def __init__(self, offset, name):
self.__offset = timedelta(hours=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
utc = FixedOffset(0, "UTC")
Then to parse the time string, you could use strptime():
dt = datetime.strptime("2014/08/19 03:38:46 GMT-4", "%Y/%m/%d %H:%M:%S GMT-4")
aware = dt.replace(tzinfo=FixedOffset(-4, "GMT-4"))
print(aware) # -> 2014-08-19 03:38:46-04:00
print(aware.astimezone(utc)) # -> 2014-08-19 07:38:46+00:00

Categories