Based on the example I found here I want to grab icalendar data and process it. This my code so far:
from datetime import datetime, timedelta
from icalendar import Calendar
import urllib
import time
ics = urllib.urlopen('https://www.google.com/calendar/ical/xy/basic.ics').read()
ical1 = Calendar.from_ical(ics)
for vevent in ical1.subcomponents:
if vevent.name == "VEVENT":
title = str(vevent.get('SUMMARY').encode('utf-8'))
start = vevent.get('DTSTART').dt # datetime
end = vevent.get('DTEND').dt # datetime
print title
print start
print end
print type(start)
print "---"
It is fetching the title and start+end date from my google calender. This working and the output looks like this:
This is a Test Title
2012-12-20 15:00:00+00:00
2012-12-20 18:00:00+00:00
<type 'datetime.datetime'>
---
Another Title
2012-12-10
2012-12-11
<type 'datetime.date'>
---
...
As you can see the start and end date can be of type datetime.datetime or datetime.date. It depends on whether I have an entry in google calender for 2 whole days (then it is a datetime.date) or for a time period e.g. 3 hours (then it is a datetime.datetime. I need to only print dates/datetimes from today and for the next 4 weeks. I had problems comparing dates and datetimes (its seems like it is not possible) so I failed to do that. How can I compare datetimes and dates conserving the data types? If I need to "cast" them, its ok. I was not able to print "today + 4 weeks", only "4 weeks".
You will need to convert to a common type for comparison. Since both datetime's and date's have dates in common, it makes sense to convert -> date types. Just extract the date() from the datetime. For example:
>>> import datetime
>>> datetime.date(2014, 2, 22) == datetime.datetime.now().date()
True
Datetime objects can return an appropriate date object by calling date on them: start.date() which then can be compared to another date object: start.date() < datetime.date.today() + datetime.timedelta(4*7)
Related
I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
With python, How can I check if a date stored in a string has already passed?
My current code:
from datetime import date, datetime
date1 = date.today()
data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')
print(date1<=data2_obj)
The code above gives me the following error:
TypeError: can't compare datetime.datetime to datetime.date
Note that I would not want to work with any time - just the date (this case the treated in 32287708)
Use the .date() method to get the date component like this:
from datetime import date, datetime
date1 = date.today()
date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)
Output:
False
I have a date column in my dataframe that consists of strings like this...'201512'
I would like to convert it into a datetime object of just year to do some time series analysis.
I tried...
df['Date']= pd.to_datetime(df['Date'])
and something similar to
datetime.strptime(Date, "%Y")
I am not sure how datetime interfaces with pandas dataframes (perhaps somebody will comment if there is special usage), but in general the datetime functions would work like this:
import datetime
date_string = "201512"
date_object = datetime.datetime.strptime(date_string, "%Y%m")
print(date_object)
Getting us:
2015-12-01 00:00:00
Now that the hard part of creating a datetime object is done we simply
print(date_object.year)
Which spits out our desired
2015
More info about the parsing operators (the "%Y%m" bit of my code) is described in the documentation
I would look at the module arrow
https://arrow.readthedocs.io/en/latest/
import arrow
date = arrow.now()
#example of text formatting
fdate = date.format('YYYY')
#example of converting text into datetime
date = arrow.get('201905', 'YYYYMM').datetime
I have some measurements that happened on specific days in a dictionary. It looks like
date_dictionary['YYYY-MM-DD'] = measurement.
I want to calculate the variance between the measurements within 7 days from a given date. When I convert the date strings to a datetime.datetime, the result looks like a tuple or an array, but doesn't behave like one.
Is there an easy way to generate all the dates one week from a given date? If so, how can I do that efficiently?
You can do this using - timedelta . Example -
>>> from datetime import datetime,timedelta
>>> d = datetime.strptime('2015-07-22','%Y-%m-%d')
>>> for i in range(1,8):
... print(d + timedelta(days=i))
...
2015-07-23 00:00:00
2015-07-24 00:00:00
2015-07-25 00:00:00
2015-07-26 00:00:00
2015-07-27 00:00:00
2015-07-28 00:00:00
2015-07-29 00:00:00
You do not actually need to print it, datetime object + timedelta object returns a datetime object. You can use that returned datetime object directly in your calculation.
Using datetime, to generate all 7 dates following a given date, including the the given date, you can do:
import datetime
dt = datetime.datetime(...)
week_dates = [ dt + datetime.timedelta(days=i) for i in range(7) ]
There are libraries providing nicer APIs for performing datetime/date operations, most notably pandas (though it includes much much more). See pandas.date_range.