I want to find out the following:
given a date (datetime
object), what is the corresponding day of the week?
For instance, Sunday is the first day, Mond
import datetime
int(datetime.datetime.today().strftime('%w'))+1
this should give you your real day number - 1 = sunday, 2 = monday, etc...
datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :
from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")
The output that you get from this is 'Mon'
. If you want the output as 'Monday', use the following :
parser.parse('January 11, 2010').strftime("%A")
This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.
Below is the code to enter date in the format of DD-MM-YYYY you can change the input format by changing the order of '%d-%m-%Y' and also by changing the delimiter.
import datetime
try:
date = input()
date_time_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
print(date_time_obj.strftime('%A'))
except ValueError:
print("Invalid date.")
import datetime
import calendar
day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])
08 05 2015
Friday
If you have dates as a string, it might be easier to do it using pandas' Timestamp
import pandas as pd
df = pd.Timestamp("2019-04-12")
print(df.dayofweek, df.weekday_name)
Output:
4 Friday
Say you have timeStamp: String variable, YYYY-MM-DD HH:MM:SS
step 1: convert it to dateTime function with blow code...
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
Step 2 : Now you can extract all the required feature as below which will create new Column for each of the fild- hour,month,day of week,year, date
df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
df['Year'] = df['timeStamp'].apply(lambda t: t.year)
df['Date'] = df['timeStamp'].apply(lambda t: t.day)