I have two dates in Python. One is received from the database:
(datetime.datetime(2017, 10, 10, 10, 10, 10),)
And the other from the email:
Thu, 18 Jan 2018 15:50:49 -0500.
I want to compare these two dates in Python for which I think these dates need to be converted in one specific format. How to convert these dates in one specific format to compare?
Convert both to datetime (very powerful with dates).
dt_date = datetime.datetime(2017, 10, 10, 10, 10, 10)
str_date = 'Thu, 18 Jan 2018 15:50:49 -0500'
pd.to_datetime([dt_date,str_date])
Output:
DatetimeIndex(['2017-10-10 10:10:10', '2018-01-18 20:50:49']
from datetime import datetime
start_date = datetime(2017, 10, 10, 10, 10, 10)
email_date = datetime.strptime("Thu, 18 Jan 2018 15:50:49", "%a, %d %b %Y %H:%M:%S")
start_date, email_date
>>>datetime.datetime(2017, 10, 10, 10, 10, 10) datetime.datetime(2018, 1, 18, 15, 50, 49)
Related
I have incoming strings that are UTC dates in ISO format like,
2021-11-21T12:16:42Z
I wish to convert these dates into PST and then subtract 12 hours from it.
import datetime
time_list_utc=2021-11-21T12:16:42Z
time_list_pst=time_list_utc.convert(pst)
print(time_list_pst-8hours)
I am new to datetime manipulation so any input is greatly appreciated
Use datetime, tzinfo and timedelta modules since Python 3.9:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
s = '2021-11-21T12:16:42Z'
# Convert to datetime (UTC)
dt_utc = datetime.strptime(utc, "%Y-%m-%dT%H:%M:%S%z")
# Convert to PST
dt_pst = dt_utc.astimezone(ZoneInfo('US/Pacific'))
# Subtract 12 hours
dt = dt_pst - timedelta(hours=12)
Output:
>>> dt
datetime.datetime(2021, 11, 20, 16, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))
>>> dt_pst
datetime.datetime(2021, 11, 21, 4, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))
>>> dt_utc
datetime.datetime(2021, 11, 21, 12, 16, 42, tzinfo=datetime.timezone.utc)
I need to set the time value of detatime objects to 00:00, so I can easily compare two 'dates'
Now I do:
extracted_start_date = datetime.strptime(extracted_start_date.strftime('%Y-%m-%d'), '%Y-%m-%d')
so I have my datetime object
$ datetime.datetime(2021, 3, 18, 11, 13, 53, 782088),
I extract the date string strftime('%Y-%m-%d')
$ '2021-03-18'
and put this back into a datetime object now wch has time 00:00
$ datetime.datetime(2021, 3, 18, 0, 0)
This seems quite elaborate, is there a more efficient way, or is it OK like this?
datetime.datetime objects have method date which return datetime.date instance and these might be used for day-based comparison, consider following example:
import datetime
d1 = datetime.datetime(2021, 3, 17, 9, 0, 0) # yesterday 9:00
d2 = datetime.datetime(2021, 3, 18, 9, 0, 0) # today 9:00
d3 = datetime.datetime(2021, 3, 18, 12, 0, 0) # today 12:00
print(d1.date() == d2.date())
print(d2.date() == d3.date())
output:
False
True
You could use the replace method instead.
from datetime import datetime
d = datetime(2021, 3, 18, 11, 13, 53, 782088)
d.replace(hour=0, minute=0, second=0, microsecond=0)
> datetime.datetime(2021, 3, 18, 0, 0)
I'm retrieving struct_time dates from Feedparser.
Like you can see below, FeedParser automatically parses the dates into GMT (second line, EDT, get converted from 19:19 to 23:19)
FeedParser converted Sun, 06 Sep 2020 23:07:16 GMT into struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))
FeedParser converted Fri, 11 Sep 2020 19:19:01 EDT into struct_time((2020, 9, 11, 23, 19, 1, 4, 255, 0))
When I try to convert the struct_time to a datetime with the below, I get GMT + 1 (my timezone).
from datetime import datetime
from time import mktime
datetime.fromtimestamp(mktime(struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))))
> datetime.datetime(2020, 9, 7, 0, 7, 16)
How can I convert these struct_time into datetimes GMT?
to get a time zone aware datetime object, you could unpack the relevant part of the timetuple into a datetime object and set the tzinfo attribute to UTC:
from datetime import datetime, timezone
# given a time_struct tuple like
s = (2020, 9, 6, 23, 7, 16, 6, 250, 0)
# convert to datetime object as
dt = datetime(*s[:6], tzinfo=timezone.utc)
print(dt)
>>> 2020-09-06 23:07:16+00:00
How do I represent a 3 letter month date format in python such as the following:
Jan 16, 2012
I know for January 16, 2012 the format is %B %d,%Y. Any ideas?
There's the three letter month format %b:
In [37]: datetime.strptime('Jan 16, 2012', '%b %d, %Y')
Out[37]: datetime.datetime(2012, 1, 16, 0, 0)
date_str = 'Jan 16, 2012'
date_components = date_str.split(' ')
date_components[0] = date_components[0][:3]
return ' '.join(date_components)
I am attempting to build a program to handle alerts. I want it to be able to handle specific dates like 8/23/2015 7:00 and relative dates like 5 days and 7 hours from now. specific dates are fine but for relative dates if I try and just add 5 days and 7 hours to the date time it can overflow the values intended for that spot
import datetime
dt = datetime.datetime.now()
dayslater = 5
hourslater = 7
minuteslater = 30
alarmTime = datetime.datetime(dt.year, dt.month, dt.day + dayslater,
dt.hour + hourslater,
dt.minute + minuteslater, 0,0)
this is fine sometimes but if dayslater was 40 days it would overflow the value. I did set up a simple
if hours >= 24:
hours -= 24
days++
however this won't work for overflowing months whose length in days isn't consistent.
Don't. Dates are hard, and it's very easy to get it wrong.
Instead, use timedelta:
In [1]: from datetime import datetime, timedelta
In [2]: dt = datetime.now()
In [3]: dt
Out[3]: datetime.datetime(2015, 7, 23, 15, 2, 55, 836914)
In [4]: alarmTime = dt + timedelta(days=5, hours=7, minutes=30)
In [5]: alarmTime
Out[5]: datetime.datetime(2015, 7, 28, 22, 32, 55, 836914)
Use a datetime.timedelta() object and leave calculations to the datetime library:
import datetime
delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater)
alarmTime = datetime.datetime.now() + delta
Demo:
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dayslater = 5
>>> hourslater = 7
>>> minuteslater = 30
>>> delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater)
>>> delta
datetime.timedelta(5, 27000)
>>> dt
datetime.datetime(2015, 7, 23, 21, 4, 59, 987926)
>>> dt + delta
datetime.datetime(2015, 7, 29, 4, 34, 59, 987926)
Note how the hours carried over to the next day (from 21:04 to 04:34), and thus the date went from the 23rd to the 29th. I did not have to worry about 'overflow' here.
This continues to work at month boundaries, at year boundaries, and in leap years, with February 29th:
>>> datetime.datetime(2015, 7, 26, 22, 42) + delta
datetime.datetime(2015, 8, 1, 6, 12)
>>> datetime.datetime(2015, 12, 26, 22, 42) + delta
datetime.datetime(2016, 1, 1, 6, 12)
>>> datetime.datetime(2016, 2, 23, 22, 42) + delta
datetime.datetime(2016, 2, 29, 6, 12)