Format date in datetime - python

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.

Related

timedelta to 12 pm CET

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'))

Python - Adding offset to time

I have a time string, say
str = "2018-09-23 14:46:55"
and an offset
offset = "0530"
I want to get str2 with offset added, ie
str2 = "2018-09-23 20:16:55"
Please guide.
You can use the datetime module:
from datetime import datetime, timedelta
x = "2018-09-23 14:46:55"
offset = "0530"
res = datetime.strptime(x, '%Y-%m-%d %H:%M:%S') + \
timedelta(hours=int(offset[:2]), minutes=int(offset[2:]))
print(res)
datetime.datetime(2018, 9, 23, 20, 16, 55)
Use timedelta to add offset to a datetime object.
from datetime import datetime, timedelta
str = "2018-09-23 14:46:55"
str = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
str2 = str + timedelta(hours=5, minutes=30)
print(str2)

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')

How to extract day, month and year from utcnow?

I have the following var: time_created = datetime.utcnow()
How to create a time_created_day var from time_created that will contain only Y, M, d
like this datetime.datetime(2017, 11, 7)
I have the following solution:
from datetime import date
time_created_day = date(time_created.year, time_created.month, time_created. day)
is it the best way?
Use datetime.utcnow().date()
datetime.utcnow().date()
datetime.date(2017, 11, 7)
Adding to answer
The datetime object always contains year, month, day as well as hours, minutes, seconds, and microseconds. It is a combination of what the date and time objects contain, see datetime Objects
from datetime import datetime
# this is your datetime object
time_created = datetime.utcnow()
# when you want to see it formatted as Y,M,D call the date method
date_created = time_created.date()
time_created
date_created
Output:
datetime.datetime(2017, 11, 7, 23, 43, 43, 761750)
datetime.date(2017, 11, 7)`
Use time_created.day to find the day.
time_created_day = time_created.day
(Similar for month and year)
here it is easiest for you
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + " " + month + " " + day;

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