Convert isoformat to datetime - python

I have a problem with converting isoformat to datetime.
I have this:
[{'timex-value': '2019-W32T15:00', 'start': 18, 'end': 31, 'text': '3pm next week', 'type': 'TIME', 'value': '2019-W32T15:00'}]
How can I convert '2019-W32T15:00' to datetime format in python?

To get a date time object you would want something like this. However you you will not get a the correct answer because you do not have a day of the week.
import date time as dt
dt.datetime.strptime('2019-W32T15:00','%Y-W%WT%H:%M')
If you want a successful conversion to a date time then specify the first day of that week by adding a 1 to the timex-value string.
import date time as dt
dt.datetime.strptime('2019-W32T15:00'+'-1','%Y-W%WT%H:%M-%w')
Result: datetime.datetime(2019, 8, 12, 15, 0)

Related

Adding days to a ISO 8601 format date in Python

I need to add +3 hours to a date in iso 8601 format in python, for example "2022-09-21T22:31:59Z" due to time difference. In this time information that is returned to me from the API, I only need Y/M/D information, but due to the +3 hour difference, the day information needs to go one step further in the date information, as will be experienced in the date I conveyed in the example. How can I overcome this problem? I think the format of the date format is ISO 8601 but can you correct me if I am wrong?
ex. api response;
"createdDateTime": "2022-09-21T22:31:59Z"
what i need;
"createdDateTime": "2022-09-21T22:31:59Z" to "2022-09-22T01:31:59Z"
Try this code it will definitely work:
from datetime import datetime,timedelta
parsed_date=datetime.strptime("2022-09-21T22:31:59Z", "%Y-%m-%dT%H:%M:%SZ")
Updated_date = parsed_date+ timedelta(hours=3)
print(Updated_date)
If you have a proper JSON string you can parse it with json, extract the string value, parse that with datetime.fromisoformat into a datetime value and then get the date from it :
import json
from datetime import datetime
data=json.loads('{"createdDateTime": "2022-09-21T22:31:59+00:00"}')
isostr=data['createdDateTime'].replace('Z','+00:00')
fulldate=datetime.fromisoformat(isostr)
fulldate.date()
-----
datetime.date(2022, 9, 21)
The replacement is necessary because fromisoformat doesn't understand Z
Adding 3 hours to fulldate will return 1 AM in the next day:
fulldate + timedelta(hours=3)
------
datetime.datetime(2022, 9, 22, 1, 31, 59, tzinfo=datetime.timezone.utc)
fulldate is in UTC. It can be converted to another timezone offset using astimezone
fulldate.astimezone(tz=timezone(timedelta(hours=3)))
---
datetime.datetime(2022, 9, 22, 1, 31, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800)))
Or in a more readable form:
fulldate.astimezone(tz=timezone(timedelta(hours=3))).isoformat()
---------------------------
'2022-09-22T01:31:59+03:00'
This is 1AM in the next day but with a +3:00 offset. This is still the same time as 22PM at UTC.
It's also possible to just replace the UTC offset with another one, without changing the time values, using replace:
fulldate.replace(tzinfo=timezone(timedelta(hours=3))).isoformat()
----------------------------
'2022-09-21T22:31:59+03:00'
That's the original time with a different offset. That's no longer the same time as 2022-09-21T22:31:59Z

Convert date/time without year to this year

I'm taking input that looks like "8-15 14:45" and trying to turn it into a datetime object (and then turn it back into a string). My issue is that it sets the year to 1900, but I need the year set to this year. How do I accomplish this?
So far I have datetime.datetime.strptime('8-15 14:45', '%m-%d %H:%M') which gives me datetime.datetime(1900, 8, 15, 14, 45) but I need datetime.datetime(2021, 8, 15, 14, 45). I'd like to not hardcode 2021 if I can help it.
Apologies if this is answered somewhere, my google-fu has failed me.
Use datetime.replace with datetime.today().year:
this_year = dt.datetime.today().year
dt.datetime.strptime('8-15 14:45', '%m-%d %H:%M').replace(year=this_year)
You can use the method now() of the datetime class and only ask for the property year of the returned datetime object:
from datetime import datetime
t = datetime.now().year
print(t)
>>> 2021
You can do this by replacing the year on the parsed date like this:
from datetime import datetime as dt
date = dt.strptime('8-15 14:45', '%m-%d %H:%M')
date = date.replace(year=dt.now().year)

How to convert a string into datetime format

I'm trying to convert strings in a list to datetime format on Python. I am unable to use pd.DateTime at the moment. The imported datetime package doesn't seem to work. I'm new to this.
Please help.
Cheers.
Code Image
You should consider using official datetime formats
Example:
from datetime import datetime
#datetime(year, month, day)
date = datetime(2018, 11, 28)
# datetime(year, month, day, hour, minute, second, microsecond)
date = datetime(2017, 11, 28, 23, 55, 59, 342380)
you can use strptime
from datetime import datetime, strptime
my_datetime_list = [strptime(string_date, '%y-%m-%d') for string_date in list_of_string_dates]

Removing time stamp when converting date format with dateparser in scrapy

I am using dateparser in scrapy to convert the date format.
Original date format: Apr 16, 2019
After using dateparser: 2019-04-16 00:00:00
This is what I wanted to achieve. However, I would still like to remove the time from the date format, so in the end, I only have 2019-04-16. Unfortunately, I am not able to realize this.
This is my line of code:
import dateparser
...
def parse_site(self, response):
def get_with_xpath(query):
return response.xpath(query).get(default='').strip()
yield {
'date': dateparser.parse(get_with_xpath('//meta[#name="date"]/#content'))
}
As I said, it works. But the time stamp I would like to remove. Any ideas?
Dateparser.parse returns datetime representing parsed date if successful. You can use strftime() function to remove the timestamp as shown below
dateparser.parse('Apr 16, 2019').strftime("%Y-%m-%d")
Methods of this library return all values in datetime format. But afterwards you are free to do with them anything you want. Check this example:
>>> import dateparser
>>> dateparser.parse("Apr 16, 2019")
datetime.datetime(2019, 4, 16, 0, 0)
>>> dateparser.parse("Apr 16, 2019").date()
datetime.date(2019, 4, 16)

How to combine between today's date and a specified time in Django/Python?

I have a case in my Django :
Variable 't' get data from database. I print 't' variable and the result is 'datetime.time(16, 59, 59)'. It means at 16:59:59.
I want to combine today's date with these time. Does anyone know?
The result that I want is (for example) : 'datetime.datetime(2014, 10, 22, 16, 59, 59)' which is combine from today's date is '2014-10-22' and specified time like '16:59:59'.
Thank you.
Use datetime.combine:
from datetime import datetime, date, time
datetime.combine(date(2014, 10, 22), time(16, 59, 59)).
its what that datetime.combine is for and date.today() returns todays date :
>>> from datetime import datetime ,date , time
>>> datetime.combine(date.today(), time(16, 59, 59))
datetime.datetime(2014, 10, 22, 16, 59, 59)

Categories