Extraction of day, month and year from the date 4.5.6 - python

Which function can I use to extract day, month and year from dates written in this manner 4.5.6 where 4 is the day, 5 is the month and 6 is the year (presumably 2006). I have already tried using dateparser.parse but it is not working.

day, month, year = map(int, '4.5.6'.split('.'))
And then add 2000 as necessary to the year.
You can then construct a datetime object with
from datetime import datetime
dt = datetime(year, month, day)
While it would be logical to use datetime.strptime, the one-digit year messes things up, and the above will just work fine.

Here is how you can use the datetime.datetime.strptime() method:
import datetime
s = "4.5.6"
i = s.rindex('.') + 1
s = s[:i] + s[i:].rjust(2, '0') # Add padding to year
dt = datetime.datetime.strptime(s, "%d.%m.%y")
print(dt)
Output:
2006-05-04 00:00:00
With the resulting datetime.datetime object, you can access plenty of information about the date, for example you can get the year by printing dt.year (outputs 2006).

Related

For-loop for days over years, python script for targeting data

If I want to add a loop to constrain days as well, what is the easiest way to do it, considering different length of month, leap years etc.
This is the script with years and months:
yearStart = 2010
yearEnd = 2017
monthStart = 1
monthEnd = 12
for year in list(range(yearStart, yearEnd + 1)):
for month in list(range(monthStart, monthEnd + 1)):
startDate = '%04d%02d%02d' % (year, month, 1)
numberOfDays = calendar.monthrange(year, month)[1]
lastDate = '%04d%02d%02d' % (year, month, numberOfDays)
If you want only the days then this code, using the pendulum library, is probably the easiest.
>>> import pendulum
>>> first_date = pendulum.Pendulum(2010, 1, 1)
>>> end_date = pendulum.Pendulum(2018, 1, 1)
>>> for day in pendulum.period(first_date, end_date).range('days'):
... print (day)
... break
...
2010-01-01T00:00:00+00:00
pendulum has many other nice features. For one thing, it's a drop-in replacement for datetime. Therefore, many of the properties and methods that you are familiar with using for that class will also be available to you.
You may want to use datetime in addition to calendar library. I am exactly not sure on requirements. But it appears you want the first date and last date of a given month and year. And, then loop through those dates. The following function will give you the first day and last day of each month. Then, you can loop between those two dates in whichever way you want.
import datetime
import calendar
def get_first_last_day(month, year):
date = datetime.datetime(year=year, month=month, day=1)
first_day = date.replace(day = 1)
last_day = date.replace(day = calendar.monthrange(date.year, date.month)[1])
return first_day, last_day
Adding the logic for looping through 2 dates as well.
d = first_day
delta = datetime.timedelta(days=1)
while d <= last_day:
print d.strftime("%Y-%m-%d")
d += delta

Formatting string into datetime using Pandas - trouble with directives

I have a string that is the full year followed by the ISO week of the year (so some years have 53 weeks, because the week counting starts at the first full week of the year). I want to convert it to a datetime object using pandas.to_datetime(). So I do:
pandas.to_datetime('201145', format='%Y%W')
and it returns:
Timestamp('2011-01-01 00:00:00')
which is not right. Or if I try:
pandas.to_datetime('201145', format='%Y%V')
it tells me that %V is a bad directive.
What am I doing wrong?
I think that the following question would be useful to you: Reversing date.isocalender()
Using the functions provided in that question this is how I would proceed:
import datetime
import pandas as pd
def iso_year_start(iso_year):
"The gregorian calendar date of the first day of the given ISO year"
fourth_jan = datetime.date(iso_year, 1, 4)
delta = datetime.timedelta(fourth_jan.isoweekday()-1)
return fourth_jan - delta
def iso_to_gregorian(iso_year, iso_week, iso_day):
"Gregorian calendar date for the given ISO year, week and day"
year_start = iso_year_start(iso_year)
return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)
def time_stamp(yourString):
year = int(yourString[0:4])
week = int(yourString[-2:])
day = 1
return year, week, day
yourTimeStamp = iso_to_gregorian( time_stamp('201145')[0] , time_stamp('201145')[1], time_stamp('201145')[2] )
print yourTimeStamp
Then run that function for your values and append them as date time objects to the dataframe.
The result I got from your specified string was:
2011-11-07

Get a datetime format from a string in Python

Hello sorry for the ambiguous title, here's what I want to do :
I have a string:
month = '1406'
that corresponds to the month of June, 2014.
How can I dynamically say that that string represents the month of June and I specifically want the last day of the month.
So I want to write it in the format: '%Y-%m-%d %H:%M:%S' and have:
'2014-06-30 00:00:00'
You get the last day of a given month with the calendar.monthrange() function. Turn your string into two integers (month, year), create a datetime object from the year, month and last day of the month:
from datetime import datetime
from calendar import monthrange
year, month = int(month[:2]), int(month[2:])
year += 2000 # assume this century
day = monthrange(year, month)[1]
dt = datetime(year, month, day) # time defaults to 00:00:00
Demo:
>>> from datetime import datetime
>>> from calendar import monthrange
>>> month = '1406'
>>> year, month = int(month[:2]), int(month[2:])
>>> year += 2000 # assume this century
>>> day = monthrange(year, month)[1]
>>> datetime(year, month, day)
datetime.datetime(2014, 6, 30, 0, 0)
>>> print datetime(year, month, day)
2014-06-30 00:00:00
The default string conversion for datetime objects fits your desired format already; you can make it explicit by calling str() on it or by using the datetime.datetime.isoformat() method, as you see fit.
This seems to do the trick:
import datetime
mon = '1406'
y, m = divmod(int(mon), 100)
dt = datetime.datetime(2000 + y + m // 12, m % 12 + 1, 1) - datetime.timedelta(days=1)
print dt

Get date from week number

Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)
The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00
%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.

Find next date by day of week [duplicate]

This question already has answers here:
How do I get the day of week given a date?
(30 answers)
Closed 9 years ago.
I'm using "datetime" and am having trouble figuring out how to grab the date in the format "%Y-%M-%d" by day of the week. For example:
Since today is 2013-04-01 (a Monday), what code would grab the following Tuesday or Thursday? (output should be 2013-04-02 - Tuesday)
Or if the date is 2013-04-02, a Tuesday, what code would grab the next Mon, Wed, or Fri? (output should be 2013-04-03 - Next day or Wednesday)
Thanks,
This works:
import datetime as dt
dow={d:i for i,d in
enumerate('Mon,Tue,Wed,Thu,Fri,Sat,Sun'.split(','))}
def next_dow(d,day):
while d.weekday()!=day:
d+=dt.timedelta(1)
return d
d1=min(next_dow(dt.datetime(2013,4,1),day)
for day in (dow['Tue'],dow['Thu']))
d2=min(next_dow(dt.datetime(2013,4,2),day)
for day in (dow['Mon'],dow['Wed'],dow['Fri']))
for d in d1,d2:
print d.strftime('%Y-%m-%d')
Or (perhaps better but less general):
def next_dow(d,days):
while d.weekday() not in days:
d+=dt.timedelta(1)
return d
d1=next_dow(dt.datetime(2013,4,1),(dow['Tue'],dow['Thu']))
d2=next_dow(dt.datetime(2013,4,2),(dow['Mon'],dow['Wed'],dow['Fri']))
for d in d1,d2:
print d.strftime('%Y-%m-%d')
Prints:
2013-04-02
2013-04-03
You could try something like this:
from datetime import datetime
from datetime import timedelta
def return_next_tues_thur(dt):
while True:
dt += timedelta(days=1)
dow = dt.strftime(%w)
if dow == 2 || dow == 4:
return dt
dt = datetime.now() # Or you set it: dt = datetime(2013, 4, 1)
next_tues_thur = return_next_tues_thur(dt)
print next_tues_thur.strftime("%Y-%m-%d")
This uses the strftime method and the %w modifier to get the day-of-week from a datetime object. (%w will return an int in the range 0 to 6 where zero is Sunday.)
This idea should be easily extensible to Monday/Wednesday/Friday.

Categories

Resources