Calling a datetime object as string in Python - python

I have a slice function in Python that slices parse dates like "1960-01-01". I have tried to assign variables to make the code generic, However, when the data is not called like this :
calibration_period = slice('1960-01-01', '2000-12-31')
validation_period = slice('2001-01-01', '2014-12-31')
and called like:
calibration_period = slice(Base, Date[-1])
validation_period = slice(Date2[0],Date2[-1])
The last value is read as 2014-12-31 00:00:00, but I want to read it as "2014-12-31" so the calculations continue up to 2014-12-31 23:00:00.
I have used this:
from datetime import datetime
t=pd.to_datetime(str(Date2[-1]))
strg=t.strftime('%Y-%m-%d')
although the print function shows it as 2014-12-31 the print for validation is still:
slice(numpy.datetime64('2001-01-01T00:00:00.000000000'), Timestamp('2014-12-31 00:00:00'), None)
I would be really grateful if someone has a suggestion.

I think the issue is you're mixing up datetime formats and string formats.
from datetime import datetime
time = datetime.strptime('01/01/2010', '%d/%m/%Y')
newtime = datetime.strftime(time, '%d/%m/%Y')
print(time, newtime)
2010-01-01 00:00:00 01/01/2010
Press any key to continue . . .
Convert your date times to a string with the format you want using datetime.strftime, then you can use logic to do the calculation, i.e:
A datetime object with value 2010-01-01 23:30:00 will always be converted to a string of type 2010-01-01 when using:
value = datetime.strftime(value, '%Y-%m-%d')
Can then perform logic on the two strings
if value == newtime:
print(value)
Full example:
from datetime import datetime
time = datetime.strptime('01/01/2010 20:30:30', '%d/%m/%Y %H:%M:%S')
newtime = datetime.strftime(time, '%d/%m/%Y')
print(time)
print(newtime)
#Outputs:
2010-01-01 20:30:30
01/01/2010

May be helpful
>>> from datetime import datetime
>>> d = datetime.utcnow()
>>> d.date()
datetime.date(2018, 7, 10)
>>> str(d.date())
'2018-07-10'

Related

How to change date formet using Python?

I want to change date format using Python. I don't know How to do that.
I have date format as shown below
2020-10-22 12:14:41.293000+00:00
I want to change above date format into below format:
date(2020, 10, 22)
I want this format because I want to get different between two dates.
with above format I can get difference by using following code,
d0 = date(2017, 8, 18)
d1 = date(2017, 10, 26)
delta = d1 - d0
print(delta.days)
So how to Change date Format as I discussed above.and also let me know if anyone know other way to get difference between these two dates 2020-10-22 12:14:41.293000+00:00 and 2020-10-25 12:14:41.293000+00:00 without changing its formet.I will be thankful if anyone can help me with this issue.
use fromisoformat and date() to get only the date, without the time:
from datetime import datetime
d = datetime.fromisoformat('2020-10-22 12:14:41.293000+00:00').date()
# d
# datetime.date(2020, 10, 22)
To convert a string to a datetime object, we use the datetime module.
from datetime import datetime
def str_to_date(s):
s = s.split()[0] # Separate the str by spaces and get the first item (the date)
s = datetime.strptime(s, "%Y-%m-%d")
return s # You now have a datetime object to do operations on.
If the format is always in the form YYYY-MM-DD ..... then you can strip the first 10 characters of the date and use datetime to convert into datetime object
from datetime import datetime
unformatted_date = "2020-10-22 12:14:41.293000+00:00"
date_obj = datetime.strptime(unformatted_date[0:11], "%Y-%m-%d").date()
print(date_obj)
Change string to datetime format:
from datetime import datetime
date1 = datetime.strptime('2020-10-22 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
date2 = datetime.strptime('2020-10-23 12:14:41.293000+00:00', '%Y-%m-%d %H:%M:%S.%f%z').date()
print(date2-date1)
#1 day, 0:00:00

Remove time in date format in Python

I using:
s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')
I need convert a number in date format (2020-01-13)
but when I print final:
2020-01-13 00:00:00
Tried datetime.date(s, '%Y%m%d') but It's returns a error:
an integer is required (got type str)
Is there any command to get only date without hour?
Once you have a datetime object just use strftime
import datetime
d = datetime.datetime.now() # Some datetime object.
print(d.strftime('%Y-%m-%d'))
which gives
2020-02-20
You can use strftime to convert back in the format you need :
import datetime
s = "20200113"
temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00
final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13
Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.
s = "20200113"
year = int(s[:4]) # 2020
month = int(s[4:6]) # 1
day = int(s[6:8]) # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'
You can also convert directly via strings.
>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'
You can use .date() on datetime objects to 'remove' the time.
my_time_str = str(final.date())
will give you the wanted result

Parse only time, and set date to today?

I am trying to convert a time string into a datetime object where the date is today's date. However, I only have a time string and its replace() method does not seem to work.
from datetime import datetime, time,date
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
print startTime
>>> 1900-01-01 09:30:00
I want:
2017-01-20 09:30:00
nicer than replace is combine:
timestr = "9:30"
startTime = datetime.strptime(timestr,"%H:%M")
d = datetime.combine(datetime.today(), startTime.time())
replace doesn't work in-place. Don't ignore the return value, assign it back like this:
startTime = startTime.replace(year=datetime.now().year, month=datetime.now().month, day=datetime.now().day)
and you get:
2017-01-20 09:30:00
Here is another solution using another library.
import pendulum
timestr = "9:30"
dt = pendulum.parse(timestr)
<Pendulum [2017-01-20T09:30:00+00:00]>
Or
dt = pendulum.parse(timestr).to_datetime_string()
'2017-01-20 09:30:00'

How can I get all the dates within a week of a certain day using 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.

parsing month year pairs into datetime

Let's say i have 2 strings 'Jan-2010' and 'Mar-2010' and i want to parse it such that it returns 2 datetime objects: 1-Jan-2010 and 31-Mar-2010 (i.e. the last day).
What would be the best strategy in python? Should i just split the string into tokens or use regular expressions and then use the calendar functions to get say the last day of the month for 'Mar-2010' (getting the first day is trivial, its always 1 in this case unless i wanted the first working day of the month).
Any suggestions? Thanks in advance.
strptime does the string parsing into dates on your behalf:
def firstofmonth(MmmYyyy):
return datetime.datetime.strptime(MmmYyyy, '%b-%Y').date()
much better than messing around with tokenization, regexp, &c!-).
To get the date of the last day of the month, you can indeed use the calendar module:
def lastofmonth(MmmYyyy):
first = firstofmonth(MmmYyyy)
_, lastday = calendar.monthrange(first.year, first.month)
return datetime.date(first.year, first.month, lastday)
You could ALMOST do it neatly with datetime alone, e.g., an ALMOST working approach:
def lastofmonth(MmmYyyy):
first = firstofmonth(MmmYyyy)
return first.replace(month=first.month+1, day=1
) - datetime.timedelta(days=1)
but, alas!, this breaks for December, and the code needed to specialcase December makes the overall approach goofier than calendar affords;-).
I highly recommend using the python timeseries module, which you can download and read about here:
http://pytseries.sourceforge.net/
You should also use the dateutil package for parsing the date string, which you can find here:
http://labix.org/python-dateutil
Then you can do something like this
import datetime
import dateutil.parser
import scikits.timeseries as TS
m1 = TS.Date('M', datetime=dateutil.parser.parse('Jan-2010'))
m2 = TS.Date('M', datetime=dateutil.parser.parse('Mar-2010'))
d1 = m1.asfreq('D', relation='START') # returns a TS.Date object
d2 = m2.asfreq('D', relation='END')
firstDay = d1.datetime
lastDay = d2.datetime
This solution is dependent out outside modules, but they're very powerful and well written.
from datetime import datetime, timedelta
def first_day(some_date):
return some_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
def next_month(some_date):
return first_day(first_day(some_date) + timedelta(days=31))
def last_day(some_date):
return next_month(some_date) - timedelta(days=1)
# testing:
months = [('Jan-2010', 'Mar-2010'), # your example
('Apr-2009', 'Apr-2009'), # same month, 30 days
('Jan-2008', 'Dec-2008'), # whole year
('Jan-2007', 'Feb-2007')] # february involved
for date1, date2 in months:
print first_day(datetime.strptime(date1, '%b-%Y')),
print '-',
print last_day(datetime.strptime(date2, '%b-%Y'))
That prints:
2010-01-01 00:00:00 - 2010-03-31 00:00:00
2009-04-01 00:00:00 - 2009-04-30 00:00:00
2008-01-01 00:00:00 - 2008-12-31 00:00:00
2007-01-01 00:00:00 - 2007-02-28 00:00:00
i know it's long time gone, but if someone needs:
from dateutil import rrule
from dateutil import parser
from datetime import datetime
first_day = parser.parse('Jan-2010',default=datetime(1,1,1))
last_day = rrule.rrule(rrule.MONTHLY,count=1,bymonthday=-1, bysetpos=1,dtstart=parser.parse('Mar-2010'))
Riffing on Alex Martelli's:
import datetime
def lastofmonthHelper(MmmYyyy): # Takes a date
return MmmYyyy.replace(year=MmmYyyy.year+(MmmYyyy.month==12), month=MmmYyyy.month%12 + 1, day=1) - datetime.timedelta(days=1)
>>> for month in range(1,13):
... t = datetime.date(2009,month,1)
... print t, lastofmonthHelper(t)
...
2009-01-01 2009-01-31
2009-02-01 2009-02-28
2009-03-01 2009-03-31
2009-04-01 2009-04-30
2009-05-01 2009-05-31
2009-06-01 2009-06-30
2009-07-01 2009-07-31
2009-08-01 2009-08-31
2009-09-01 2009-09-30
2009-10-01 2009-10-31
2009-11-01 2009-11-30
2009-12-01 2009-12-31
You don't have to use the first day of the month, BTW. I would have put this in a comment but we all know how the formatting would have turned out. Feel free to upvote Alex.
If you call with the result of a firstofmonth() call, you get the desired result:
>>> lastofmonthHelper(firstofmonth('Apr-2009'))
datetime.date(2009, 4, 30)

Categories

Resources