Convert paypal date to string in python - string

paypal is giving me this format '03:00:00 Mar 14, 2023 PDT'. I've tried different solutions but i can't get with the right one. How can i separate each item into a string using python?

Assuming you want a datetime object
from datetime import datetime
time_string = "03:00:00 Mar 14, 2023 PDT"
d = datetime.strptime(time_string[:-4], "%H:%M:%S %b %d, %Y")
or
import parsedatetime as pdt # $ pip3 install parsedatetime
cal = pdt.Calendar()
time_string = "03:00:00 Mar 14, 2023 PDT"
d = cal.parseDT(time_string)[0]
Once you have your datetime, output the part(s) you want using strftime

Related

How to get the date in the form of month(string) day(int) year(int)?

I was wondering how to get the date in the form of month(string) day(int) year(int) using only python?
You can use dparser to get something similar:
import dateutil.parser as dparser
from datetime import datetime, date
today = date.today()
print(datetime.date(dparser.parse(str(today),fuzzy=True)).strftime("%B, %d, %Y"))
OUTPUT:
April, 24, 2020

Python convert time zones deviation

I want to use Python to convert times to UTC and compare them. In my experiment, the Tokyo time has a deviation and I do not know if it is a mistake of my approach or a bug?
Code
#!/usr/bin/env python3
import datetime
tz = pytz.timezone("Asia/Tokyo")
date = datetime.datetime.strptime(
'12:00',
'%H:%M'
)
date_with_tz = tz.localize(date)
print("Time in Tokyo\t\t: ", date_with_tz.strftime('%H:%M'))
date_as_utc = date_with_tz.astimezone(pytz.utc)
print("Time Tokyo in UTC\t: ", date_as_utc.strftime('%H:%M'))
print("Should 12 (Tokyo) -> 3 (UTC)")
Output
❯ ./time_zone.py
Time in Tokyo : 12:00
Time Tokyo in UTC : 02:41
The UTC time should be 3 and not 2:41 ... what is happening here?
You don't need to use localize in this case.
import datetime, pytz
tokyo = datetime.datetime.now(pytz.timezone("Asia/Tokyo")).replace(hour=12, minute=0, second=0)
utc = tokyo.astimezone(pytz.utc)
print("Time Tokyo:", tokyo.strftime('%H:%M'))
print("Time UTC:", utc.strftime('%H:%M'))
print("Should 12 (Tokyo) -> 3 (UTC)")

Convert date string to datetime for whole column of df

df = pd.read_csv('bitcoin.csv')
print(df)
gives
Date Open High Low Close Volume
0 Apr 16, 2018 8337.57 8371.15 7925.73 8058.67 5,631,310,000
1 Apr 15, 2018 7999.33 8338.42 7999.33 8329.11 5,244,480,000 ....
I tried
pd.to_datetime(pd.Series(['Date']), format = '%b %d, %Y')
but got
TypeError: Unrecognized value type: && ValueError: time data 'Date' does not match format '%b %d %Y' (match)
I also tried
df['Date'] = df['Date'].apply(lambda x: datetime.datetime.strptime(x, '%b %d, %Y')
but got SyntaxError: unexpected EOF while parsing
when running
print(df['Date'])
after printing it says
Name: Date, Length: 1567, dtype: object
Not sure whats going on here? Is it already a datetime object?
Seems like you're missing an extra parenthesis at the end here:
df['Date'] = df['Date'].apply(lambda x: datetime.datetime.strptime(x, '%b %d, %Y'))
I would suggest you do something like this, adding to #COLDSPEED comment:
df['Date'] = df['Date'].apply(lambda x: pd.to_datetime(x, format = '%b %d, %Y', errors = 'coerce'))
df['Date'] = pd.to_datetime(df.Date).dt.strftime('%b %d, %Y')
Output
0 Apr 16, Jan 01, 1970
1 Apr 15, Jan 01, 1970
Name: Date, dtype: object

Syntax Error <expression Line 1>

I'm trying to convert a date in a string format (13/06/2017) into a date format June 13, 2007. I have written the code but I keep getting a syntax error for my first line which is the definition of the function line.
My code is this:
def printDate(date):
import datetime
newdate = datetime.strptime(date, %d/%m/%Y)
d = newdate.strftime(%b %d, %Y)
return d
You didn't pass the parameter "date format" as a string, that's why, also be sure to import datetime module as follows:
from datetime import datetime
def printDate(date):
newdate = datetime.strptime(date, "%d/%m/%Y")
d = newdate.strftime("%B %d, %Y")
return d
Test:
printDate("13/06/2017")
>> 'June 13, 2017'

Convert dates to specific format

I have a pandas dataframe that looks like:
import pandas as pd
df1 = pd.DataFrame({'Counterparty':['Bank','Client','Bank','Bank','Bank','Bank'],
'Date':['4Q18','1Q19','2Q19','4Q21','FY22','H123']
})
I want to convert the 'Date' column from a string to a date such that the date is the last date for that particular period. ie 'FQ18'= 31st Dec 2018, '1Q19' = 31st Mar 2019, 'FY22' = 31st Dec 2022,'H123'= 30th June 2023
Any suggestions how to achieve this ?
As mentioned by #jpp, you're going to have to do some customization. There isn't existing functionality to map "FY22" to 2022-12-31, to my knowledge. Here's something to get you started, based on the limited example you've shown:
import re
import pandas as pd
from pandas.core.tools.datetimes import DateParseError
from pandas.tseries import offsets
halfyr = re.compile(r'H(?P<half>\d)(?P<year>\d{2})')
fiscalyr = re.compile(r'FY(?P<year>\d{2})')
def try_qend(date):
try:
return pd.to_datetime(date) + offsets.QuarterEnd()
except (DateParseError, ValueError):
halfyr_match = halfyr.match(date)
if halfyr_match:
half, year = [int(i) for i in halfyr_match.groups()]
month = 6 if half == 1 else 12
return pd.datetime(2000 + year, month, 1) + offsets.MonthEnd()
else:
fiscalyr_match = fiscalyr.match(date)
if fiscalyr_match:
year = int(fiscalyr_match.group('year'))
return pd.datetime(2000 + year, 12, 31)
else:
# You're SOL
return pd.NaT
def parse_dates(dates):
return pd.to_datetime([try_qend(date) for date in dates])
Assumptions:
All years are 20yy, not 19xx.
The regex patterns here completely describe the year-half/fiscal-year syntax set.
Example:
dates = ['4Q18','1Q19','2Q19','4Q21','FY22','H123']
parse_dates(dates)
DatetimeIndex(['2018-12-31', '2019-03-31', '2019-06-30', '2021-12-31',
'2022-12-31', '2023-06-30'],
dtype='datetime64[ns]', freq=None)

Resources