Python 3.6 Weekday - python

I have a combination date/time string 20180104 06:09:36.234 from which I want to find the weekday in python, expecting to get the result for for the date (which is 04 January 2018) as "4" (ie Thursday) . Have searched far and wide to no avail.Can anyone help please?
Thanks CJ

See explanation of datetime.strptime
from datetime import datetime
date_string = '20180104 06:09:36.234'
date = datetime.strptime(date_string, '%Y%m%d %H:%M:%S.%f')
print(date.isoweekday()) # 4

Finally worked it out by various combinations of functions:
Identify year, month, date,
Convert to integer,
Use datetime module.
import datetime
DateTime = '20180104 06:09:36.234'
Weekday = datetime.date(int(DateTime[0:4]), int(DateTime[5:6]),
int(DateTime[7:8])).weekday()
print("Weekday = " , Weekday)
Weekday = 3
Is there a better way??

Related

Extract day of the week and hour from iso datetime stamp in Python

How can I extract the day of the week and the hour of the day from a timestamp in this format?
2020-08-17T01:54:38.000Z
So for the example above I would get Monday and 01 in return.
You could parse the string into a datetime object using strptime with a custom format, and then extract the info you need from it:
from datetime import datetime
dateStr = '2020-08-17T01:54:38.000Z'
dt = datetime.strptime(dateStr,'%Y-%m-%dT%H:%M:%S.%fZ')
hour = dt.strftime('%H')
dayOfWeek = dt.strftime('%A')

Use current month/day in datetime parse

I'm trying to parse a string that is just '07:43 PM'. I figured out the strptime() function but when I print the result the day, month and year are all wrong. It's not using the current time, it uses 1, 1 and 1900 respectively. A naive solution to this I found would be to just use .replace() and replace the day, month and year with the current values. Is there something else I can do?
y = '07:43 PM'
print(datetime.strptime(y, '%I:%M %p')) #1900-01-01 19:43:00
As the comment said you can get the now time then update those fields with what you want such as:
from datetime import datetime
y = '07:43 PM'
now, stripped = datetime.now(), datetime.strptime(y, '%I:%M %p')
now = now.replace(hour=stripped.hour, minute=stripped.minute)
print(now)

How can I convert text to DateTime?

I scraped a website and got the following Output:
2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
Is there a way I can take the first one and convert it into a DateTime value?
Just parse the string into year, month, day, hour and minute integers and then create a new date time object with those variables.
Check out the datetime docs
You can convert string format of datetime to datetime object like this using strptime, here %z is the time zone :
import datetime
dt = "2018-06-07T12:22:00+0200"
ndt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S%z")
# output
2018-06-07 12:22:00+02:00
The following function (not mine) should help you with what you want:
df['date_column'] = pd.to_datetime(df['date_column'], format = '%d/%m/%Y %H:%M').dt.strftime('%Y%V')
You can mess around with the keys next to the % symbols to achieve what you want. You may, however, need to do some light cleaning of your values before you can use them with this function, i.e. replacing 2018-06-07T12:22:00+0200 with 2018-06-07 12:22.
You can use datetime lib.
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.strptime documentation
Solution here

String to date formatting

I have a string of the following format:
x = '2018-02-15-11'
I need to convert this to a date format. I have tried:
from datetime import date
from datetime import time
from datetime import datetime
dhs = '2018-02-15-11'
x = datetime.strptime(dhs, '%Y-%M-%d-%H')
print x
However, the output is
2018-01-15 11:02:00
I need the output in the format (as date object):
2018-01-15-11
Am I missing something here?
I think there could be a mistake on your part, you have used %Y-%M-%d-%H where %M indicates minutes, not month. But according to the look, it should be %m i.e. month.
Answering your original question, the format specifiers for strftime (datetime to string) and strptime (string to datetime) are the same. So you can use datetime.datetime.strftime('%Y-%m-%d-%H') like:
In [47]: dhs = '2018-02-15-11'
...: x = datetime.datetime.strptime(dhs, '%Y-%m-%d-%H')
...: print(x.strftime('%Y-%m-%d-%H'))
...:
2018-02-15-11
I've used %m instead of %M here. If you are really sure about this, use %M if you want.
N.B: You are getting same string you've started with.

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.

Categories