I need to compare dates in this format:
'03/31/2018' # month/day/year
I tried to use the datetime module:
from datetime import datetime as dt
dt.strptime("03/31/2018", "%m/%d/%y")
But I got this error:
ValueError: unconverted data remains: 18
If I use a two digit year:
dt.strptime("03/31/18", "%m/%d/%y")
It works, but in this case I need to compare using the whole four digits year
You need to use a big Y
>>> from datetime import datetime as dt
>>> dt.strptime("03/31/2018", "%m/%d/%Y")
datetime.datetime(2018, 3, 31, 0, 0)
Related
I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass
I am given a number like: 737556.5965277777.
>>> datetime.timedelta(days=737556.5965277777)
datetime.timedelta(days=737556, seconds=51539, microseconds=999996)
>>> datetime.datetime.now()
datetime.datetime(2020, 5, 11, 15, 36, 41, 711686)
How can I compare this with the current datetime to check whether it is after? Either get the current timedelta and compare those or convert it to a timestamp first, then compare.
One way would be to convert the current datetime to an ordinal, and then compare the two. If the ordinal datetime is greater than the now() ordinal datetime, then it is after.
You can use datetimes toordinal()
from datetime import datetime as dt
dt_now = dt.now()
ordinal_date = dt_now.toordinal()
print(ordinal_date)
The ordinal datetime is just a number of day starting with date 0001-01-01 (as day 1). So you can just add the timedelta (minus one day, to compensate for 0001-01-01 not being day 0) to that date:
yourdate = datetime.datetime(1,1,1) + datetime.timedelta(days=737556.5965277777 - 1)
and compare it to now:
if yourdate > datetime.datetime.now():
Note that yourdate.toordinal() returns the integer part of your initial number: 737556.
I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'
Given a string that looks like "Hours:5 Minutes:34 Seconds:28" or "Minutes:34 Seconds:28", is there any pythonic way to convert it to a datetime object? I do not want to use a regex if there's an easier way.
Yes, there is. You can do it like this:
import time
datetime_string = "Hours:5 Minutes:34 Seconds:28"
if "Hours" in datetime_string:
datetime_object = time.strptime(datetime_string, "Hours:%H Minutes:%M Seconds:%S")
elif "Minutes" in datetime_string:
datetime_object = time.strptime(datetime_string, "Minutes:%M Seconds:%S")
else:
datetime_object = time.strptime(datetime_string, "Seconds:%S")
Note: When You create datetime object, values that You do not provide will be filled with default values.So, in case datetime_string contains only seconds, hours and minutes will be set to 0.
You may use datetime.strptime() to convert string into datetime object as:
>>> from datetime import datetime
>>> date_object = datetime.strptime('Hours:5 Minutes:34 Seconds:28', 'Hours:%H Minutes:%M Seconds:%S')
>>> date_object
datetime.datetime(1900, 1, 1, 5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
Since you do not have date in the string, it will keep the default date of 1 Jan 1990. I think what you need is datetime.time() which return time object with same hour, minute, second and microsecond as in you datetime object. (tzinfo is None). For example:
>>> date_object.time()
datetime.time(5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
where date_object is of datetime type created earlier.
A function returns date and time in unicode format.
u'2014-03-06T04:38:51Z'
I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.
Thanks in advance
Check string is unicode
>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True
Converting strings to datetime:
>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)
Subtract from today to
>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)
First you have to convert your string to a datetime.datetime object.
import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")
then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.
now = datetime.datetime.now()
Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.
for delta in (now-then, then-now):
print(delta, "::", delta.days, delta.seconds, delta.microseconds)
This prints out:
-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858
Best try it with a few examples to convince yourself it's correct.