I found a curious bug.
When I used the library wx, my function strptime, which comes of datetime library, doesn't work.
Example :
from datetime import datetime
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
When I execute the previous code and wx.app() I have the following error:
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
Traceback (most recent call last):
File "<ipython-input-108-b41842200da1>", line 1, in <module>
myDate2= datetime.strptime('Wed Feb 19 14:57:58 2020', '%a %b %d %H:%M:%S %Y')
File "C:\Simu\WinPython_3741\python-3.7.4.amd64\Lib\_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Simu\WinPython_3741\python-3.7.4.amd64\Lib\_strptime.py", line 359, in _strptime
(data_string, format))
ValueError: time data 'Wed Feb 19 14:57:58 2020' does not match format '%a %b %d %H:%M:%S %Y'
What is the link between the datetime and wx ?
And how to fix this bug ?
Resolved !
This bug comes from localtime. I don't know why but when I execute wx.app(), my localtime change.
I discovered this thanks to the following command :
from time import strftime,localtime
print(strftime("%H:%M, %d %B %Y",localtime()))
10:44, 20 février 2020
To change the localtime, here is the code :
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
Related
I'm trying to make a simple clock and I want the format to have the numeric hour without a padding zero. According to every source I can find on google the symbol for that is %l but that gives me a traceback error? It works fine if I use %I though.
def count():
global time1
global date1
time2 = time.strftime('%l:%M %p')
date2 = time.strftime('%A, %B %d %Y')
if time2 != time1:
time1 = time2
clock.config(text=time2)
if date2 != date1:
date1=date2
date.config(text=date2)
clock.after(500, count)
Traceback (most recent call last):
File "D:/Program Files (x86)/pycharm/Projects/test.py", line 48, in count
time2 = time.strftime('%l:%M %p')
ValueError: Invalid format string
Process finished with exit code 1
You want %-I:
time2 = time.strftime('%-I:%M %p')
http://strftime.org/ is a nice reference for Python's strftime format strings.
This is what I have:
pat = '%Y-%m-%d %H:%M:%S +0000'
my_time = time.strptime(task_time, pattern)
But, how can I change the timezone from:
my_time:
2016-06-15 23:27:52 +0000
to a different timezone:
PDT
or
-0700
So the result is:
result = 2016-06-15 16:27:52 -0700
Using the python package arrow this simple script can be used:
import arrow
fmt = "YYYY-MM-DD HH:mm:ss Z"
time = arrow.get("2016-06-15 23:27:52 +0000", fmt)
time = time.to("US/Pacific")
print(time.format(fmt))
2016-06-15 16:27:52 -0700
Install arrow with pip install arrow
Edit: If you do not want to use the arrow package:
import time
import calendar
fmt = "%Y-%m-%d %H:%M:%S "
t = calendar.timegm(time.strptime("2016-06-15 23:27:52 +0000", fmt + "+0000"))
t -= 8 * 60 * 60
s = time.strftime(fmt + "-0700", time.gmtime(t))
print(s)
Note, that this is horrible code and if you use this in production you will definitely get fired from your job, so just install the arrow package!
I'm Salech and I'm learning Python. Python is my really first programming language. It is my second day that I following the youtube video "from zero to hero". And my first problem that I can't solve is related to time and date.
The challenge:
Ask a user to enter a deadline for their project
Tell them how many days they have to complete the project
For Extra Credit give them the answer as a combination of weeks & days
I made all of that, but then I thought to add an additional feature, which takes an input of time(hh:mm:ss) and prints this time minus the current time. Here's how I thought to do it:
import math
import datetime
currentDate = datetime.date.today()
currentTime = datetime.datetime.now()
deadLine = input('Hello, enter the deadline date for your project (mm/dd/yyyy)')
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
deadLineTime = input('insert time')
deadTime = datetime.datetime.strptime(deadLineTime, '%H:%M:%S').time()
print(deadTime)
daysLeft = deadLineDate - currentDate
print('%d days left' % daysLeft.days)
weeksLeft = math.floor(daysLeft.days/7)
newDaysLeft = daysLeft .days- 7*(math.floor(daysLeft.days/7))
print('You have %d weeks' % weeksLeft, ' and %d days left.' % newDaysLeft)
timeLeft = deadTime - currentTime
print(timeLeft.hours)
With the input 02/04/2016 and 15:00 I get the following error:
Hello, enter the deadline date for your project (mm/dd/yyyy)02/04/2016
insert time15:00
15:00:00
5 days left
You have 0 weeks and 5 days left.
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 31, in <module>
timeLeft = deadTime - currentTime
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.datetime'
>>>
Edit: As jonatan said, testing the code without any input:
Hello, enter the deadline date for your project (mm/dd/yyyy)
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 14, in <module>
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 507, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 344, in _strptime
(data_string, format))
ValueError: time data '' does not match format '%m/%d/%Y'
Thank You.
You need to combine your date and your time into a datetime.
deadline = datetime.datetime.combine(deadLineDate, deadlineTime)
timeLeft = deadline - currentTime
The reason for the error is because it doesn't really make much sense to subtract a date from a time. e.g. What is "4PM - Fri, Jan 29th?".
import datetime
import math
currentDate=datetime.date.today()
currentTime=datetime.datetime.now()
UserInput1=input("What is the deadline for your project? mm/dd/yyyy ")
deadLine=datetime.datetime.strptime(UserInput1, "%m/%d/%Y").date()
UserInput2=input("Please insert the time hh/mm/ss ")
deadTime=datetime.datetime.strptime(UserInput2, "%H/%M/%S").time()
daysLeft= deadLine-currentDate
print("%d days left" % daysLeft.days)
weeksLeft=math.floor(daysLeft.days/7)
newDaysLeft=daysLeft.days-7*(math.floor(daysLeft.days/7))
print("You have %d weeks" % weeksLeft, "and %d days left."% newDaysLeft)
deadLine=datetime.datetime.combine(deadLine,deadTime)
timeLeft=deadLine-currentTime
print(timeLeft)
I can't seem to figure out how to convert a datetime string to another datetime string with timezone.
Here's the example.
07/27/2015:06:00 AM to 20150727060000 -0400
The default timezone would be EST.
Here's my code so far.
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
Use pytz module to work with timezones in Python. To get the local timezone as pytz tzinfo object, you could use tzlocal module:
from tzlocal import get_localzone # $ pip install tzlocal
naive = _to_datetime('07/27/2015', '06:00 AM')
aware = get_localzone().localize(naive, is_dst=None)
print(aware.strftime('%Y%m%d%H%M%S %z'))
# -> 20150727060000 -0400
Add the time zone to the parsed string with %z. This will give it a tzinfo attribute:
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time + ' -0400', '%m/%d/%Y:%I:%M %p %z')
Example:
>>> datetime.strptime('03/19/2015:03:00 PM -0400','%m/%d/%Y:%I:%M %p %z')
datetime.datetime(2015, 3, 19, 15, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
You could use dateutil to add the tzinfo to the datetime object.
from datetime import datetime, timedelta
from dateutil import tz
AmericaNewYorkTz = tz.gettz('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p').replace(tzinfo=AmericaNewYorkTz)
dt = _to_datetime('07/27/2015', '06:00 AM')
print('DateTime:', dt)
# DateTime: 2015-07-27 06:00:00-04:00
or as J.H. Sebastian pointed out, you can use pytz
from datetime import datetime, timedelta
from pytz import timezone
AmericaNewYorkTz = timezone('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
naiveDateTime = datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
localizedDateTime = AmericaNewYorkTz.localize(naiveDateTime, is_dst=None)
return localizedDateTime
dt = _to_datetime('05/27/2015', '06:00 AM')
print('DateTime:', dt)
In Python, with TwitterSearch, I'm able to get the timestamp of the tweet in UTC time, in the following format :
Thu Mar 19 12:37:15 +0000 2015
However, I would like to obtain it automatically in the EST timezone (UTC - 4), in this format :
2015-03-19 08:37:15
Here is a sample of my code. What should I change in it for an automatic conversion?
for tweet in ts.search_tweets_iterable(tso):
lat = None
long = None
user = tweet['user']['screen_name']
user_creation = tweet['user']['created_at']
created_at = tweet['created_at'] # UTC time when Tweet was created.
favorite = tweet['favorite_count']
retweet = tweet ['retweet_count']
id_status = tweet['id']
in_reply_to = tweet['in_reply_to_screen_name']
followers = tweet['user']['followers_count'] # nombre d'abonnés
statuses_count = tweet['user']['statuses_count'] # nombre d'abonnés
location = tweet['user']['location'] # résidence du twittos
tweet_text = tweet['text'].strip() # deux lignes enlèvent espaces inutiles
tweet_text = ''.join(tweet_text.splitlines())
print i,created_at,user_creation,user, tweet_text
if tweet['geo'] and tweet['geo']['coordinates'][0]:
lat, long = tweet['geo']['coordinates'][:2]
print u'#%s: %s' % (user, tweet_text), lat, long
else:
print u'#%s: %s' % (user, tweet_text)
print favorite,retweet,id_status,in_reply_to,followers,statuses_count,location
writer.writerow([user.encode('utf8'), user_creation.encode('utf8'), created_at.encode('utf8'),
tweet_text.encode('utf8'), favorite, retweet, id_status, in_reply_to, followers, statuses_count, location.encode('utf8'), lat, long])
i += 1
if i > max:
return()
Thank you in advance!
Florent
If EST is your local timezone then you could do it using only stdlib:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz('Thu Mar 19 12:37:15 +0000 2015'))
s = str(datetime.fromtimestamp(timestamp))
# -> '2015-03-19 08:37:15'
It supports non-UTC input timezones too.
Or you could specify the destination timezone explicitly:
import pytz # $ pip install pytz
dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
s = dt.strftime('%Y-%m-%d %H:%M:%S')
# -> '2015-03-19 08:37:15'
You could put it in a function:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
def to_local_time(tweet_time_string):
"""Convert rfc 5322 -like time string into a local time
string in rfc 3339 -like format.
"""
timestamp = mktime_tz(parsedate_tz(tweet_time_string))
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')
# use time_string here..
Remove the +0000 from the date sent by twitter and do something like:
from datetime import datetime
import pytz
local = 'Europe/London' #or the local from where twitter date is coming from
dt = datetime.strptime("Thu Mar 19 12:37:15 2015", "%a %b %d %H:%M:%S %Y")
dt = pytz.timezone(local).localize(dt)
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output:
2015-03-19 07:37:15
Alternatively you can do something like (in this case you don't need to remove the +0000 timezone info):
from dateutil import parser
dt = parser.parse("Thu Mar 19 12:37:15 +0000 2015")
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output
2015-03-19 07:37:15
By the way, EST is UTC-4 or UTC-5?