Xlxswriter - Change Date format from str to date - python

I am having trouble changing the date format of date column in the dataframe i created using Xlsxwriter. The current format is 3/31/2016 12:00:00 AM, which i thought python is reading a date and adding a time to it. I would like the format to simply be dd/mm/yyyy with know time associate with it for all of column A.
Here is my code:
date_format= workbook.add_format({'num_format': 'mmm d yyyy'})
date_time= dt.datetime.strftime("%m/%d/%Y")
worksheet.write_datetime(0,0, date_time, date_format)
The error message i get is : TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

datetime.strftime is for converting datetimes into strings
You are not giving it a datetime object to convert.
from datetime import datetime
today = datetime.today() # this returns a datetime object
today.strftime("%m/%d/%Y") # this returns a string
datetime.strftime(today, "%m/%d/%Y") # alternative way to call it
However, you actually need to pass a datetime object to worksheet.write_datetime
So in my example it would be like this
today = datetime.today()
date_format= workbook.add_format({'num_format': 'mmm d yyyy'})
worksheet.write_datetime(0, 0, today, date_format)
To parse a date from a string use date time.strptime
dateobj = date time.strptime(datestr)

Related

How to convert Datetime ("2020-09-27 07:14:01.114051200") to week number?

I want to find the week number of a date column in my datasets. The date is in the format "2020-09-27 07:14:01.114051200". However I could not convert to week number.
I tried the below code:
date=mydate.strftime("%W")
I'm getting this error: AttributeError: 'Series' object has no attribute 'strftime'
You need to first convert your date in string form to a datetime object. Then you can ask for the week number from that object.
import datetime
datestr = "2020-09-27 07:14:01.114051200"
mydate = datetime.datetime.strptime(datestr.split('.')[0] , '%Y-%m-%d %H:%M:%S')
date=mydate.strftime("%W")
print(date)
Result:
38

Comparison between datetime and datetime64[ns] in pandas

I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
I'm using:
cur_date = datetime.today()
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evaluates to false
I do know for a fact that today's date is in the file in question. The dtype of the series is datetime64[ns]
Also, I am only checking the date itself and not the timestamp afterwards, if that matters. I'm doing this to make the timestamp 00:00:00:
cur_date = datetime.strptime(cur_date.strftime('%Y_%m_%d'), '%Y_%m_%d')
And the type of that object after printing is datetime as well
For anyone who also stumbled across this when comparing a dataframe date to a variable date, and this did not exactly answer your question; you can use the code below.
Instead of:
self.df["date"] = pd.to_datetime(self.df["date"])
You can import datetime and then add .dt.date to the end like:
self.df["date"] = pd.to_datetime(self.df["date"]).dt.date
You can use
pd.Timestamp('today')
or
pd.to_datetime('today')
But both of those give the date and time for 'now'.
Try this instead:
pd.Timestamp('today').floor('D')
or
pd.to_datetime('today').floor('D')
You could have also passed the datetime object to pandas.to_datetime but I like the other option mroe.
pd.to_datetime(datetime.datetime.today()).floor('D')
Pandas also has a Timedelta object
pd.Timestamp('now').floor('D') + pd.Timedelta(-3, unit='D')
Or you can use the offsets module
pd.Timestamp('now').floor('D') + pd.offsets.Day(-3)
To check for membership, try one of these
cur_date in df['date'].tolist()
Or
df['date'].eq(cur_date).any()
When converting datetime64 type using pd.Timestamp() it is important to note that you should compare it to another timestamp type. (not a datetime.date type)
Convert a date to numpy.datetime64
date = '2022-11-20 00:00:00'
date64 = np.datetime64(date)
Seven days ago - timestamp type
sevenDaysAgoTs = (pd.to_datetime('today')-timedelta(days=7))
convert date64 to Timestamp and see if it was in the last 7 days
print(pd.Timestamp(pd.to_datetime(date64)) >= sevenDaysAgoTs)

How to convert strftime or string format to timestamp/Date in python?

I am very new to Python coding. I was trying to get the start and end date of a month and then compare it with another date column in the same excel.
I only need the date in mm/dd/yy format but do not need the time.
The final_month_end_date is basically a string format which I compare with an actual date but it gives me an error saying
"TypeError: Cannot compare type 'Timestamp' with type 'str'"
I have also tried .timestamp() function but of no use.
How can I resolve this problem?
import datetime as dt
import strftime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= calendar.monthrange(current_year,current_month)[1]
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
To convert a string to a DateTime object use datetime.strptime. Once you have the datetime object, convert it to a unix timestamp using time.mktime.
import time
import datetime as dt
from time import mktime
from datetime import datetime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= "30"
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
# Use datetime.strptime to convert from string to datetime
month_start = datetime.strptime(month_start_date, "%Y/%m/%d")
month_end = datetime.strptime(final_month_end_date, "%Y/%m/%d")
# Use time.mktime to convert datetime to timestamp
timestamp_start = time.mktime(month_start.timetuple())
timestamp_end = time.mktime(month_end.timetuple())
# Let's print the time stamps
print "Start timestamp: {0}".format(timestamp_start)
print "End timestamp: {0}".format(timestamp_end)

python parse string in date format to get the date

There is a string and a date format. I want to get the date based on format.
If date format is YYYY.MM.dd and string is 2017.01.01. It should transform to a valid date object.
How can I find the date.
You can use datetime module something like this :
from datetime import datetime
date_object = datetime.strptime('2017.01.01', '%Y.%m.%d') # Converting the given date string into a datetime object.
formatted_date = date_object.strftime('%c') #User Defined Output Format
print(formatted_date)
This will result in :
Sun Jan 1 00:00:00 2017
You can refer to the documentation here.

replace hours in a datetime type python

I have a datetime type mydate in %Y-%m-%dT%H:%M:%S format.
I want to replace the hours
I did this using mydate.replace() method
Now I want to comapre it with another specific date -> myNEWdate whose format is %Y-%m-%d %H:%M:%S :
newdate = mydate.replace(hour = islot)
print newdate
appointmentDict[mydate]['time_start'] = datetime.strptime(str(newdate),"%Y/%m/%d %H:%M:%S")
The date is printed as 2015-06-26 08:00:00
and I get the error
ValueError: time data '2015-06-26 08:00:00' does not match format '%Y/%m/%d %H:%M:%S'
What should I do to resolve this
You need to set the correct format
datetime.strptime(str(newdate),"%Y-%m-%d %H:%M:%S")
To solve the exception. Although converting from datetime 2 string and backwards doesn't make much sense, as mentioned in the comments.

Categories