Comparing two dates in different format with python - python

I have 2 dates defined as a strings. If I would know the original date format, I would compare it like this:
import time
date1 = "1/1/2013 12:00:00 AM" # formatted like "%m/%d/%Y %H:%M:%S %p"
date2 = "1/1/2016" # formatted like "%m/%d/%Y"
format1 = "%m/%d/%Y %H:%M:%S %p"
format2 = "%m/%d/%Y"
if time.strptime(date1, format1) > time.strptime(date2, format2):
pass
How can I compare it if I do not know the date format?

How can I compare it if I do not know the date format?
You can't.
Every comparison assumes that you know what you are comparing.

You can try to parse it with dateutil.parser.parse. This method parse a string in one of the supported formats. And then compare it.
datautil is a third-party module.

Related

How to convert the string to date time format?

I have the following string 20211208_104755, representing date_time format. I want to convert it to the python datetime format using datetime.strip() method.
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%y/%m/%d')
However I am getting the following error.
ValueError: time data '20211208' does not match format '%y/%m/%d'
The second argument in strptime has to match the pattern of your datetime string. You can find the patterns and their meaning on https://docs.python.org/3/library/datetime.html
In your case, you can format it as
from datetime import datetime
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print(datetime_object)
>>> 2021-12-08 10:47:55
what should work is to define how the mydatetime string is composed.
example:
%Y is the year (4 digits); check here for format (section strftime() Date Format Codes)
So in your example I would assume it's like this:
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print (datetime_object)
result
2021-12-08 10:47:55
and
type(datetime_object)
datetime.datetime

I have a date string with the format '12/Sep/21'. I want to change the format to '2021-09-12'. How can I do this in Python?

I have a date string with the format '12/Sep/21'. I want to change the format to '2021-09-12'. How can I do this in Python?
I tried this:
dte1 = '02/Sep/21'
dte2 = datetime.datetime.strptime(dte1, '%d %b %y').strftime('%d/%m/%Y')
dte2
You may mean by:
import datetime
dte1 = '02/Sep/21'
dte2 = datetime.datetime.strptime(dte1, '%d/%b/%y').strftime('%Y-%m-%d')
print(dte2)
Output:
2021-09-02
It’s so easy to convert a date format into your desired date format by using the datetime package of Python:
import datetime
your_date = '02/Sep/21'
desire_format = datetime.datetime.strptime(your_date, '%d/%b/%y').strftime('%Y-%m-%d')
print(desire_format)
Output
2021-09-02

string convert to date time in python

I have a list of date time strings like this.
16-Aug-2019
I want to convert the string to 2019-08-01 this date format, and I have tried on this code , but it's getting me an error.
formatd_date = datetime.strptime(formatd_date, '%y-%m-%d')
ValueError: time data 'As-of' does not match format '%y-%m-%d'
If any can help, it will be huge thank.
Convert to datetime format and then convert to string format you want to:
>>> from datetime import datetime
>>> a = "16-Aug-2019"
>>> datetime.strptime(a, "%d-%b-%Y").strftime("%Y-%m-%d")
'2019-08-16'
Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Just fails because %y is 2-digit year. Use %Y for 4-digit year.

How to format date to 1900's?

I'm preprocessing data and one column represents dates such as '6/1/51'
I'm trying to convert the string to a date object and so far what I have is:
date = row[2].strip()
format = "%m/%d/%y"
datetime_object = datetime.strptime(date, format)
date_object = datetime_object.date()
print(date_object)
print(type(date_object))
The problem I'm facing is changing 2051 to 1951.
I tried writing
format = "%m/%d/19%y"
But it gives me a ValueError.
ValueError: time data '6/1/51' does not match format '%m/%d/19%y'
I couldn't easily find the answer online so I'm asking here. Can anyone please help me with this?
Thanks.
Parse the date without the century using '%m/%d/%y', then:
year_1900 = datetime_object.year - 100
datetime_object = datetime_object.replace(year=year_1900)
You should put conditionals around that so you only do it on dates that are actually in the 1900's, for example anything later than today.

how to subtract date from date from sql in python

I run a sql query that returns a date in the format '2015-03-01T17:09:00.000+0000' I want to subtract this from today's date.
I am getting today's date with the following:
import datetime
now = datetime.datetime.now()
The formats don't seem to line up and I can't figure out a standardize format.
You can use strptime from datetime module to get python compatible date time from your query result using a format string. (You might have to play with the format string a bit to suit your case)
ts = '2015-03-01T17:09:00.000+0000' to a format string like
f = '%Y-%m-%dT%H:%M:%S.%f%z'
date_from_sql = datetime.datetime.strptime(ts, f)
now = datetime.datetime.now()
delta = date_from_sql - now
The .000 is probably microseconds (denoted by %f in the format string) and the +0000 is the utc offset (denoted by %z in the format string). Check this out for more formatting options: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Check out this thread for an example: what is the proper way to convert between mysql datetime and python timestamp?
Checkout this for more on strptime https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
Getting the delta between two datetime objects in Python is really simple, you simply subtract them.
import datetime
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()
delta = d2 - d1
print delta.total_seconds()
d2 - d1 returns a datetime.timedelta object, from which you can get the total second difference between the two dates.
As for formatting the dates, you can read about formatting strings into datetime objects, and datetime objects into string here
You'll read about the strftime() and strptime() functions, and with them you can get yourself two datetime objects which you can subtract from each other.

Categories

Resources