I am having problem getting some datetime conversions. I am actually using django and in one of model field I used date field not datetime field. Now I need to show time difference and I got the snippet for that from djangosnippets. But that accepts timestamp.
So I am confuse that what actually is python timestamp and how can it be made. I tried different things as in below lines:
publish_date.timetuple()
but this says, that 'datetime.date' object has no attribute 'mktime'.I guess datetime.datetime has this mktime but not datetime.date so I can't use that.
int(parse(publish_date).strftime('%s'))
Here parse is from a third party module named dateutil but this time it gives following error.
datetime.date' object has no attribute 'read'
And it gives same error for following code:
humanizeTimeDiff(publish_date)
So any better idea or approach that I should try to convert datetime.date object to timestamp. It seems like converting datetime.datetime would be also helpful. But how ?
Since you don't have any time information in your database (only date), you can only calculate the difference in number of days. To do that, simply subtract the date objects. This will yield a timedelta object which represents the difference between two date (or datetime) objects.
>>> d1
datetime.date(2012, 9, 16)
>>> d2
datetime.date(2012, 9, 17)
>>> d2-d1
datetime.timedelta(1)
>>> print d2-d1
1 day, 0:00:00
>>> print (d2-d1).days
1
Related
This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 4 months ago.
I have a JSON that returns a date in the following date format:
datetime(2015, 12, 1)
So the key value from JSON is
'CreateDate': datetime(2015, 1, 1)
In order to be able to subtract two dates, I need to convert above to date format:
YYYY/MM/DD
so in above case that would become: 2015/12/01
Is there a smart way to do that? Is it at all possible? Or do I really have to parse it as a block of text? I tried using datetime.strptime, but I can't get it to work.
datetime(2015,12,1).strftime("%Y/%m/%d")
will do the trick for you. A complete python program would look like this.
# import the datetime and date classes from the datetime module
from datetime import datetime, date
# create your datetime(..) instance from your JSON somehow
# The included Python JSON tools do not usually know about date-times,
# so this may require a special step
# Assume you have a datetime now
dt = datetime(2015,12,1)
# Print it out in your format
print( dt.strftime("%Y/%m/%d") )
Two important details:
You are using just a date in a Python datetime. Nothing wrong with that but just note that the Python datetime module also has a date class
You can enable your JSON encoder/decoder to recognise dates and datetimes automatically but it requires extra work.
Now, to subtract datetimes from each other they should remain as instances of the datetime class. You can not subtract datetimes from each other once they have been formatted as a string.
Once you subtract a Python datetime from an other datetime the result will be an instance of the timedelta class.
from datetime import datetime, timedelta
# time_diff here is a timedelta type
time_diff = datetime(2015,12,1) - datetime(2014,11,1)
Now you can look up the Python timedelta type and extract the days, hours, minutes etc. that you need. Be aware that timedeltas can be a negative if you subtract a later datetime from an earlier one.
The datetime module has a function for doing this which is pretty easy as shown below
from datetime import datetime
print(datetime(2015,12,1).strftime("%Y/%m/%d"))
Also read more about the module here https://docs.python.org/3/library/datetime.html
I have the following dates:
4/29/2020
5/7/2020
9/10/2020
10/5/2020
11/20/2020
The dates extracted from Oracle are correctly read as datetime objects in Python. However, when I manually add dates to the list in Excel, the program sees the date as string and crashes.
invalid input for query argument $1: '9/10/2020' (expected a datetime.date or datetime.datetime instance, got 'str')
This is what I am doing:
if isinstance(my_date,str):
my_date = date.fromisoformat(my_date)
It's not working. Is there a way to automatically convert a date in any format to datetime object? Thanks!
You can convert your code to something like this:
from datetime import datetime
if isinstance(my_date,str):
my_date = datetime.strptime(my_date, '%m/%d/%Y')
Yes there is : datetime.strptime
You can find documentation on how to use it here : https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
I have a list containing datetime.date() objects. I am trying to find the index of a specific date object.
I tried this -
>> index = date_obj.index(datetime.date(2009, 1, 31))
>> *** TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
But when I tried this it worked -
>> index = date_obj.index(datetime.strptime("2009-01-31","%Y-%m-%d").date())
>> 10
You imported datetime.datetime as datetime
from datetime import datetime
datetime.date is part of the base library, not datetime.datetime
You should just import datetime and use datetime.datetime and datetime.date explicitly or use something like the following to avoid these issues.
from datetime import datetime as dt
You have probably used
from datetime import datetime
and the problem is that date is part of the datetime library not from the datetime.datetime module ;)
I get from third-party service string with time. It looks like PT8H30M. What is the time format and how it convert into datetime object in Python 2.7
If we assume that the format gives only hours and minutes, you can use datetime.datetime.strptime() to parse these out, and return a datetime.time object from the result:
>>> from datetime import datetime
>>> datetime.strptime('PT8H30M', 'PT%HH%MM').time()
datetime.time(8, 30)
I'm trying to prettify ObjectIDs timestamp with py-pretty but it keeps giving me a TypeError:
TypeError: can't compare offset-naive and offset-aware datetimes
even after I attempt convert the timestamp to a timezone unaware UTC date with Pytz. This is the code I'm trying
import datetime
import pytz
import pretty
# ...
song = db.songs.find_one( { 'GUID' : 0123 } )
dateTimeUnaware = song['_id'].generation_time.now(pytz.utc)
prettyDate = pretty.date( dateTimeUnaware )
Why does this keep giving me the type error? Shouldn't the pytz function make it timezone agnostic?
I'm not a py-pretty expert, but your code doesn't convert timezone-aware date to timezone unaware date.
It just takes the current date (using now) in the utc timezone (so timezone aware).
You can naively convert tz-aware datetime to tz-unaware one by using:
your_datetime_var.replace(tzinfo=None)
in your case:
song['_id'].generation_time.replace(tzinfo=None)
Note that "naively" in this case means that all fields related to date and time will have the same value as the original one, but the information about timezone and DST will be lost.
BTW it looks like py-pretty is unmaintained (last upload to pypi in 2010, source code inaccessible) so it might be a good idea to look for replacement