Is there a way to get the format of a given string to be parsed with the datetime format?
Something like:
string_date= '2/1/99'
date_obj = parser.parse(string_date)
format1 = date_obj.getdateformat
format2 = anotherobj.getdateformat
Related
reference_date is 02.03 but I would like to convert it to Month and Date (3rd of February) so as to export to Excel as type 'date'.
reference_date = tr.find('td').text
reference_date = '2023.' + reference_date
reference_date_str = reference_date
reference_date_obj = datetime.strptime(reference_date_str, '%y-%m-%d')
You need to make sure you pass a format that matches the structure of your string.
if the string is using dots, then the format structure should be similar.
This should do the trick:
reference_date = tr.find('td').text
reference_date_with_year = f"2023.{reference_date}"
reference_date_obj = datetime.strptime(reference_date_with_year, '%Y.%m.%d')
print(reference_date_obj)
output:
2023-02-03 00:00:00
reference_date = '2023.' + reference_date
reference_date_obj = datetime.strptime(reference_date_str, '%Y.%m.%d')
excel_date=reference_date_obj.strftime("%Y.%m.%d")
if you are using pandas to write to excel sheet, you can pass the date in any format as long as you specify the format in your stmt
pd.ExcelWriter("abc.xlsx",engine='xlsxwriter',date_format='YYYY.MM.DD')
I want to extract the date (eg.2018-07-16) from strings (eg. 2018-07-16 10:17:53.460035).
The strings have two formats: "2018-07-16 10:17:53.460035" and "2018-05-20 14:37:21".
When I use strptime(d, "%Y-%m-%d %H:%M:%S.%f") to convert the strings before extracting the date, it pops this error:
ValueError: time data '2018-05-20 14:37:21' does not match format
%Y-%m-%d %H:%M:%S.%f'
How can I convert both time formats to DateTime type and extract date from it?
Use to_datetime from pandas.
import pandas as pd
a = "2018-07-16 10:17:53.460035"
b = "2018-05-20 14:37:21"
print(pd.to_datetime(a).date())
print(pd.to_datetime(b).date())
You don't need the .%f at the end for the first format, that is what is causing the format error.
t = "2018-05-20 14:37:21"
strptime(t, "%Y-%m-%d %H:%M:%S")
You need to create a second format for the other time string:
t = "2018-07-16 10:17:53.460035"
strptime(t, "%Y-%m-%d %H:%M:%S.%f")
Edit: Here is another example which excepts both
time_stamps = ["2018-05-20 14:37:21", "2018-07-16 10:17:53.460035"]
for stamp in time_stamps:
fmt = "%Y-%m-%d %H:%M:%S"
try:
time = datetime.datetime.strptime(stamp, fmt+".%f")
except ValueError:
time = datetime.datetime.strptime(stamp, fmt)
print(time)
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.
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)
I have an column in excel which has dates in the format ''17-12-2015 19:35". How can I extract the first 2 digits as integers and append it to a list? In this case I need to extract 17 and append it to a list. Can it be done using pandas also?
Code thus far:
import pandas as pd
Location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(Location)
time = df['Creation Date'].tolist()
print (time)
You could extract the day of each timestamp like
from datetime import datetime
import pandas as pd
location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(location)
timestamps = df['Creation Date'].tolist()
dates = [datetime.strptime(timestamp, '%d-%m-%Y %H:%M') for timestamp in timestamps]
days = [date.strftime('%d') for date in dates]
print(days)
The '%d-%m-%Y %H:%M'and '%d' bits are format specififers, that describe how your timestamp is formatted. See e.g. here for a complete list of directives.
datetime.strptime parses a string into a datetimeobject using such a specifier. dateswill thus hold a list of datetime instances instead of strings.
datetime.strftime does the opposite: It turns a datetime object into string, again using a format specifier. %d simply instructs strftime to only output the day of a date.