I have tried a wealth of options and got it down with like some hacked together parsing but I am curious how to do this with strptime?
item = "01/Jul/1995:00:00:01-0400"
checkdate = datetime.strptime(item,"%Y-%m-%dT:%H:%M%S%z")
checkdate = datetime.strptime(item,"%Y/%m/%dT:%H:%M:%S%z")
checkdate = datetime.strptime(item,"%Y-%b-%d:%H:%M%S%z")
checkdate = datetime.strptime(item,"%Y-%b-%dT:%H:%M:%S%z")
checkdate = datetime.strptime(item,"%Y/%m/%d:%H:%M:%S%z")
what i get for each attempt is :
ValueError: time data '01/Jul/1995:00:00:01-0400' does not match format '%Y/%m/%d:%H:%M:%S%z'
what is the correct strptime formatting for this?
EDIT:
so you were correct and i did a small test
def split_date (stringdate):
datepart = []
monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05',
'Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
split1 = [part for part in stringdate.split('/')]
day = split1[0]
month = split1[1]
month = monthDict.get(month)
split2 = [part for part in split1[2].split(":")]
year = split2[0]
hour = split2[1]
minute = split2[2]
split3 = [part for part in split2[3].split('-')]
second = split3[0]
timezone = split3[1]
return datetime(int(year), int(month), int(day), int(hour), int(minute), int(second), int(timezone)
datetime_received_split = []
datetime_received_strp = []
s = time.time()
for date in data.time_received:
try:
datetime_received_split.append(split_date(date))
except:
split_fail.append(date)
e = time.time()
print ('split took {} s '.format(e-s))
s = time.time()
for date in data.time_received:
try:
datetime_received_strp.append(datetime.strptime(item,"%d/%b/%Y:%H:%M:%S- %f"))
except:
strp_fail.append(date)
e = time.time()
print ('strp took {} s'.format(e-s))
and i found that the manual split was actually faster by a large margin?
I fixed your date conversion. What's great is %f is supported in both Python 2.7 and 3.x.
from datetime import datetime
item = "01/Jul/1995:00:00:01-0400"
checkdate = datetime.strptime(item,"%d/%b/%Y:%H:%M:%S-%f")
print(checkdate)
%z is supported in Python 3.2+.
So for Python2.x, have a look at How to parse dates with -0400 timezone string in python?
If you're using Python3.x you can try this:
from datetime import datetime
item = "01/Jul/1995:00:00:01-0400"
checkdate = datetime.strptime(item,"%d/%b/%Y:%H:%M:%S%z")
print(checkdate)
Result:
1995-07-01 00:00:01-04:00
See more details from strftime() and strptime() Behavior
Related
I need to parse exactly those publications where the publication date coincides with today's date. I only need to match the day. For example, 20 = 20. Here's what I did, but this is not good code:
today = date.today()
d2 = today.strftime("%B %d, %Y")
today_day = d2[8] + d2[9]
for el in items:
title = el.select('.card-stats > div')
p = title[1].text
space = p.replace(" ","")
day = space[1] + space[2]
if day == today_day:
data_id = el.get('data-id')
I think that the mistake could be in the second part of your code where you throw a variable, day, you didn't define before.
Try:
today = date.today()
d2 = today.strftime("%B %d, %Y")
today_day = d2[8] + d2[9]
for el in items:
title = el.select('.card-stats > div')
p = title[1].text
space = p.replace(" ","")
day = space[1] + space[2]
if today == today_day:
data_id = el.get('data-id')
So I got this error raised
ValueError: time data '8/16/2016 9:55' does not match format '%m/&d/%Y
%H:%M'.
I know that %m is the format for month with two digits (zero-padded). And as we can see that '8' (August) does not have zero padded. Is that the problem for this error? And how I fix this?
import datetime as dt
result_list = []
for a in ask_posts:
result_list.append([a[6], int(a[4])])
counts_by_hour = {}
comments_by_hour = {}
date_format = '%m/&d/%Y %H:%M'
for row in result_list:
date = row[0]
comment = row[1]
time = dt.datetime.strptime(date, date_format).strftime("%H")
``` I want to extract the Hour only```
if time not in counts_by_hour:
counts_by_hour[time] = 1
comments_by_hour[time] = comment
else:
counts_by_hour[time] += 1
comments_by_hours[time] += comment
you have an error in your dateformat % not &
import datetime as dt
result_list = []
for a in ask_posts:
result_list.append([a[6], int(a[4])])
counts_by_hour = {}
comments_by_hour = {}
date_format = '%m/%d/%Y %H:%M' # change & with %
for row in result_list:
date = row[0]
comment = row[1]
time = dt.datetime.strptime(date, date_format).strftime("%H")
``` I want to extract the Hour only```
if time not in counts_by_hour:
counts_by_hour[time] = 1
comments_by_hour[time] = comment
else:
counts_by_hour[time] += 1
comments_by_hours[time] += comment
What I am trying to do is see if date is in 1 week from currdate
from datetime import datetime, timedelta
import yagmail
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
currdate = '{}-{}-{}'.format(year, month, day)
currdate = datetime.strptime(currdate, '%Y-%m-%d')
date = '2018-04-01'
days = currdate - timedelta(int(date[-2:]))
days = str(days)
print(days)
if days[8:11] == '07':
yag = yagmail.SMTP("##########gmail.com", "######")
content = ['One Of Your Homework\'s Is Due In 1 Week!']
yag.send('###########gmail.com', 'Homework Due Soon!', content)
else:
print('It Isn\'t')
But it prints:
2018-04-07 00:00:00
It Isnt't
And I'm not sure why. Because days[8:11] is 07.
It is not 07. It's 07 (note the trailing space).
The following change will work:
if int(days[8:11]) == 7:
I'd create a function that you pass the date as a string. Something like this:
import datetime
def check_if_less_than_seven_days(x):
d = datetime.datetime.strptime(x, "%Y-%m-%d") # Add .date() if hour doesn't matter
now = datetime.datetime.now() # Add .date() if hour doesn't matter
return (d - now).days < 7
if check_if_less_than_seven_days("2018-04-18"):
print('Do something') # This will not print
if check_if_less_than_seven_days("2018-04-14"):
print('Do something') # This will print
Will print:
'Do something'
I suppose your first line when you initiate datetime.now() three times is just for testing purposes but dont do this as it could end up over different days (if you run this exactly at the milliseconds around midnight..) this will work better in that regard.
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
Anyway, read up on datetime timedelta. Just make you logic around that.
https://docs.python.org/3/library/datetime.html#timedelta-objects
import datetime
test_date_string = "2018-04-10"
d = datetime.datetime.strptime(test_date_string, "%Y-%m-%d")
now = datetime.datetime.now()
delta = d - now
elif delta.days < 7:
print("You have less then 7 days to go")
For days[8:11] you get the following output
>>> days[8:11]
'08 '
So you should use days[8:10]=='07' in case you want to use the same method,as it wont have extra space at the end.
>>> days[8:10]
'08'
so you should use
if days[8:10] == '07':
I have time string 11:15am or 11:15pm.
I am trying to convert this string into UTC timezone with 24 hour format.
FROM EST to UTC
For example: When I pass 11:15am It should convert into 15:15 and when I pass 11:15pm then it should convert to 3:15.
I have this code which I am trying:
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
# b = re.findall(r"[^\W\d_]+|\d+",a)
# c = str(int(b[0]) + 4) + ":" + b[1]
# print("c", c)
in_time = datetime.datetime.strptime(a,'%I:%M%p')
print("In Time", in_time)
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
print("Start TIme", start_time)
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time
x = appointment_time_string(time_str)
print("x", x)
But this is just converting to 24 hour not to UTC.
To convert the time from 12 hours to 24 hours format, you may use below code:
from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
In order to convert time from EST to UTC, the most reliable way is to use third party library pytz. Refer How to convert EST/EDT to GMT? for more details
Developed the following script using provided options/solutions to satisfy my requirement.
def appointment_time_string(time_str):
import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
appointment_time = str(start_date) + " " + str(start_time)
# print("Provided Time", appointment_time)
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%dT%H:%M:%SZ'
# testeddate = '2016-09-14 22:30:00'
test_date = appointment_time
dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
# print("Required Time", date_utc.strftime(fmt))
return date_utc.strftime(fmt)
I have the following time string
12:45pm - 01:00pm Today, September 7
and I want to convert this string into UTC datetime in the following format
2016-09-07T22:45:00Z
How can I achieve this in python?
developed the script to achieve it.
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S")) + "Z"
if time_str.split()[3] == 'Today,':
start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
elif time_str.split()[3] == 'Tomorrow,':
today = datetime.date.today( )
start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")
appointment_time = str(start_date) + str(start_time)
return appointment_time