Strings with start and end time to datetime - python

For a project I need to parse a few date strings. One date is given, which is the Monday of the week, for example: Feb 16, 2015.
Then, I have managed to extract a list of dates which looks like this:
['Wednesday', '11:00AM', '7:00PM']
['Friday', '10:15AM', '4:30PM']
['Sunday', '12:00AM', '5:00PM']
Where the first value is obviously the day, the second value is the starting time and the last value is the ending time (it's for events).
I would like to convert this to actual python datetime objects, but it must align with the starting date.
What I have tried so far is using this:
# Beginning of week
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y")
# List of days
for day in days:
# Find the Day of the Week
# This outputs a number, 0 = Monday, 6 = Sunday
DoW = table.index(tr)
schedule.append({
'start' : BoW + timedelta(days=DoW),
'end' : BoW + timedelta(days=DoW)
})
As you can see, this will only successfully set the date, but not the hour/minute. Is there a way to easily achieve this?

You can parse out the time with strptime() as well:
timevalue = datetime.strptime(timecomponent, '%I:%M%p').time()
%I is a 12-hour clock hour value (so between 1 and 12) and %p is the AM or PM qualifier.
You can then use datetime.datetime.combine() to combine that time component with your date:
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
start = datetime.strptime(start_time, '%I:%M%p').time()
end = datetime.strptime(end_time, '%I:%M%p').time()
start, end = datetime.combine(BoW, start), datetime.combine(BoW, end)
Demo:
>>> from datetime import datetime, timedelta
>>> BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
>>> datetime.strptime('11:00AM', '%I:%M%p').time()
datetime.time(11, 0)
>>> datetime.combine(BoW, _)
datetime.datetime(2015, 2, 16, 11, 0)

Not sure exactly what type of situation you are in, but you might try the cool NLP time parsing library parsedatetime. It would let you do something like this:
import parsedatetime
cal = parsedatetime.Calendar()
WoY_timetuple, status = cal.parse("Feb 16, 2015")
DoW_timetuple, status = cal.parse("Wednesday", sourceTime=WoY_timetuple)
start, status = cal.parseDT("11:00AM", sourceTime=DoW_timetuple)
end, status = cal.parseDT("7:00PM", sourceTime=DoW_timetuple)
So you can easily set the parsing context to get each time of day string into a full datetime object. You would need to make sure you carefully handle the status codes returned by the .parse method. If your input data has some variability in date formatting this approach could save time, otherwise Martijn's approach is probably a lot safer.

Related

Python3.7 Convert comma delimited datetime [duplicate]

This is my code:
import datetime
today = datetime.date.today()
print(today)
This prints: 2008-11-22 which is exactly what I want.
But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)
This prints the following:
[datetime.date(2008, 11, 22)]
How can I get just a simple date like 2008-11-22?
The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.
The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.
What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().
The How: what do you want to do with that?
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).
One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
for date in mylist :
print str(date)
Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)
Practical case, using your code
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
Advanced date formatting
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.
strftime() expects a string pattern explaining how you want to format your date.
E.G :
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
All the letter after a "%" represent a format for something:
%d is the day number (2 digits, prefixed with leading zero's if necessary)
%m is the month number (2 digits, prefixed with leading zero's if necessary)
%b is the month abbreviation (3 letters)
%B is the month name in full (letters)
%y is the year number abbreviated (last 2 digits)
%Y is the year number full (4 digits)
etc.
Have a look at the official documentation, or McCutchen's quick reference you can't know them all.
Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in
strftime. So you can do the same as above like this:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
Localization
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
Edit:
After Cees' suggestion, I have started using time as well:
import time
print time.strftime("%Y-%m-%d %H:%M")
The date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format
string.
Here is a list of the format codes with their directive and meaning.
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.
This is what we can do with the datetime and time modules in Python
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: ", datetime.datetime.now()
print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
That will print out something like this:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
Use date.strftime. The formatting arguments are described in the documentation.
This one is what you wanted:
some_date.strftime('%Y-%m-%d')
This one takes Locale into account. (do this)
some_date.strftime('%c')
This is shorter:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
# convert date time to regular format.
d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
OUTPUT
2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
Or even
from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
Out: '25.12.2013
or
"{} - {:%d.%m.%Y}".format("Today", datetime.now())
Out: 'Today - 25.12.2013'
"{:%A}".format(date.today())
Out: 'Wednesday'
'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())
Out: '__main____2014.06.09__16-56.log'
Simple answer -
datetime.date.today().isoformat()
With type-specific datetime string formatting (see nk9's answer using str.format().) in a Formatted string literal (since Python 3.6, 2016-12-23):
>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'
The date/time format directives are not documented as part of the Format String Syntax but rather in date, datetime, and time's strftime() documentation. The are based on the 1989 C Standard, but include some ISO 8601 directives since Python 3.6.
I hate the idea of importing too many modules for convenience. I would rather work with available module which in this case is datetime rather than calling a new module time.
>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
You need to convert the datetime object to a str.
The following code worked for me:
import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print(collection)
Let me know if you need any more help.
In Python you can format a datetime using the strftime() method from the date, time and datetime classes in the datetime module.
In your specific case, you are using the date class from datetime. You can use the following snippet to format the today variable into a string with the format yyyy-MM-dd:
import datetime
today = datetime.date.today()
print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))
In the following a more complete example:
import datetime
today = datetime.date.today()
# datetime in d/m/Y H:M:S format
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)
# datetime in Y-m-d H:M:S format
date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)
# format date
date = today.strftime("%d/%m/%Y")
print("date: %s" % time)
# format time
time = today.strftime("%H:%M:%S")
print("time: %s" % time)
# day
day = today.strftime("%d")
print("day: %s" % day)
# month
month = today.strftime("%m")
print("month: %s" % month)
# year
year = today.strftime("%Y")
print("year: %s" % year)
More directives:
Sources:
Format DateTime in Python
strftime
You can do:
mylist.append(str(today))
Considering the fact you asked for something simple to do what you wanted, you could just:
import datetime
str(datetime.date.today())
For those wanting locale-based date and not including time, use:
>>> some_date.strftime('%x')
07/11/2019
Since the print today returns what you want this means that the today object's __str__ function returns the string you are looking for.
So you can do mylist.append(today.__str__()) as well.
from datetime import date
def today_in_str_format():
return str(date.today())
print (today_in_str_format())
This will print 2018-06-23 if that's what you want :)
You may want to append it as a string?
import datetime
mylist = []
today = str(datetime.date.today())
mylist.append(today)
print(mylist)
For pandas.Timestamps, strftime() can be used e.g.:
utc_now = datetime.now()
For isoformat:
utc_now.isoformat()
For any format e.g.:
utc_now.strftime("%m/%d/%Y, %H:%M:%S")
You can use easy_date to make it easy:
import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
A quick disclaimer for my answer - I've only been learning Python for about 2 weeks, so I am by no means an expert; therefore, my explanation may not be the best and I may use incorrect terminology. Anyway, here it goes.
I noticed in your code that when you declared your variable today = datetime.date.today() you chose to name your variable with the name of a built-in function.
When your next line of code mylist.append(today) appended your list, it appended the entire string datetime.date.today(), which you had previously set as the value of your today variable, rather than just appending today().
A simple solution, albeit maybe not one most coders would use when working with the datetime module, is to change the name of your variable.
Here's what I tried:
import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present
and it prints yyyy-mm-dd.
Here is how to display the date as (year/month/day) :
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
import datetime
import time
months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date
In this way you can get Date formatted like this example: 22-Jun-2017
I don't fully understand but, can use pandas for getting times in right format:
>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>>
And:
>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']
But it's storing strings but easy to convert:
>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
maybe the shortest solution, which exactly matches your situation, would be:
mylist.append(str(AnyDate)[:10])
or even shorter, e.g.:
f'{AnyDate}'[:10]
PS: it doesn't need to be today.

What is the difference between strptime and strftime?

I am working on a project , where I have dictionary with column date called "starttime" .. I need to extract month , hour and year , day of the week.
I am stuck for now I have the below code .
{if city =='NYC':
datn = datum[('starttime')]
datn = dt.strptime(datn,"%m/%d/%y %H:%M:%S")
hour = dt.strftime(datn,"%H")
year = dt.strftime(datn,"%y")
elif city == 'Chicago':
datc = datum[('starttime')]
datc = dt.strptime(datc,"%m/%d/%y %H:%M")
month = dt.strftime(datc,"%m")
hour = dt.strftime(datc,"%H")
year = dt.strftime(datc,"%y")
else:
datw = datum[('start date')]
datw = dt.strftime (datw,"%m")
hour = dt.strftime(datw,"%H")
year = dt.strftime(datw,"%y")
return (month, hour, day_of_week)
}
my import statements are on the top of my code , as below:
from datetime import datetime
strptime translates to
"parse (convert) string to datetime object."
strftime translates to
"create formatted string for given time/date/datetime object according to specified format."
Why do you need strftime?
This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44,
377000)
To someone who isn't quite familiar with this format, with the
exception of the year, what's written up there is not immediately
intuitive. So you probably would be better off with something like
Sun, 19 July, 2015. That's what strftime is used for. You simply need
to learn the proper formatting strings.
One Good Link over SO read about this !
strptime converts the string to a datetime object.
strftime creates a formatted string for given time/date/datetime object according to specified format by the user
you would use strftime to convert a datetime object like this: datetime (2018, 10, 20, 10, 9, 22, 120401) to a more readable format like "20-10-2018" or 20th of October 2018.

Format Pandas datetime column as year-week [duplicate]

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.

With the parsedatetime library in Python, is it possible to restrict a date to the current year?

Using parsedatetime, I'd like to pass a value like Jan 1 to the calendar parser and have it return Jan 1st of the current year (which, as I post this, would be 2014-01-01).
By default, parsedatetime returns the next occurrence of the date (i.e. 2015-01-01):
>>> import parsedatetime as pdt
>>> from datetime import datetime
>>> from time import mktime
>>> cal = pdt.Calendar()
>>> datetime.now()
datetime.datetime(2014, 8, 1, 15, 41, 7, 486294)
>>> str(datetime.fromtimestamp(mktime(cal.parse('Jan 1')[0])))
'2015-01-01 14:41:13'
>>> str(datetime.fromtimestamp(mktime(cal.parse('Dec 31')[0])))
'2014-12-31 14:41:17'
I've tried inputs like last Jan 1 and Jan 1 this year without success.
Is there a way to tell the parser to return the current year's value?
Editing to add a couple requirements that weren't specified with original question:
Supports natural language processing (that's why I'm using parsedatetime)
Doesn't compromise other parsedatetime parsing functionality (like years other than current and values like yesterday and 6 months before 3/1)
Bear here - have no idea how to get my original SO profile back as I used to use ClaimID...
anywho - you can set a flag to cause parsedatetime to never go forward a year when parsing only month/day values...
import parsedatetime as pdt
ptc = pdt.Constants()
ptc.YearParseStyle = 0
cal = pdt.Calendar(ptc)
print cal.parse('Jan 1')
# ((2014, 1, 1, 15, 57, 32, 5, 214, 1), 1)
The parse function appears to take a sourceTime parameter that you can set to the 1st of the current year.
See https://bear.im/code/parsedatetime/docs/index.html
I would replace the year on your datetime object. For example :
str(datetime.fromtimestamp(mktime(cal.parse('Dec 31')[0])))
would become:
str(datetime.fromtimestamp(mktime(cal.parse('Dec 31')[0])).replace(year=datetime.today().year))
If you aren't tied to using that library (and maybe you are?) you could do it like this:
>>> import datetime
>>> datetime.datetime.now().replace(month=1, day=1).strftime("%Y-%m-%d %H:%M:%S")
'2014-01-01 22:55:56'
>>>
from datetime import date, datetime
d = datetime.strptime('Jan 1', '%b %d')
d = date(datetime.now().year, d.month, d.day)
gives datetime.date(2014, 1, 1) for d, which you can then format with
print d.strftime('%Y-%m-%d')
2014-01-01
An improved implementation based on Bear's answer.
Again this is constrained by the fact that, since this is being implemented within another DSL parser, natural_date can only accept a single string:
import parsedatetime as pdt
from datetime import datetime, date, timedelta
from time import mktime
def natural_date(human_readable):
human_readable = human_readable.lower()
# Flag to cause parsedatetime to never go forward
# https://stackoverflow.com/a/25098991/1093087
ptc = pdt.Constants()
ptc.YearParseStyle = 0
cal = pdt.Calendar(ptc)
result, parsed_as = cal.parse(human_readable)
if not parsed_as:
raise ValueError("Unable to parse %s" % (human_readable))
return date.fromtimestamp(mktime(result))
def test_natural_date():
cases = [
# input, expect
('jan 1', date(date.today().year, 1, 1)),
('dec 31', date(date.today().year, 12, 31)),
('yesterday', date.today() - timedelta(days=1)),
('3 months before 12/31', date(date.today().year, 9, 30))
]
for human_readable, expect in cases:
result = natural_date(human_readable)
print("%s -> %s" % (human_readable, result))
assert result == expect, human_readable
test_natural_date()
Credit also goes to Mark Ransom, who unearthed sourceTime parameter, which provided another way to solve this issue, although that solution was complicated by this issue.

Converting week numbers to dates

Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,date2):
while date1 < date2:
if date1.weekday() == 0:
yield date1
date1 = date1 + timedelta(days=1)
and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.
You could just feed the data into time.asctime().
>>> import time
>>> week = 6
>>> year = 2014
>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))
>>> atime
'Mon Feb 10 00:00:00 2014'
EDIT:
To convert this to a datetime.date object:
>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()
datetime.date(2014, 2, 10)
All about strptime \ strftime:
https://docs.python.org/2/library/datetime.html
mytime.strftime('%U') #for W\C Monday
mytime.strftime('%W') #for W\C Sunday
Sorry wrong way around
from datetime import datetime
mytime=datetime.strptime('2012W6 MON'. '%YW%U %a')
Strptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string.
Enjoy
A simple function to get the Monday, given a date.
def get_monday(dte):
return dte - datetime.timedelta(days = dte.weekday())
Some sample output:
>>> get_monday(date1)
datetime.date(2013, 12, 30)
>>> get_monday(date2)
datetime.date(2014, 12, 29)
Call this function within your loop.
We can 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)
To piggyback and give a different version of the answer #anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like "11-2023":
import time
from datetime import datetime
def get_date_from_week_number(str_value):
temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))
return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()

Categories