In my python code I get start and end time some thing like:
end = int(time.time())
start = end - 1800
Now start and end variables holds values like 1460420758 and 1460422558.
I am trying to convert it in a meaningful format like :
Mon Apr 11 17:50:25 PDT 2016
But am unable to do so, I tried:
time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime(start))
Gives me
Tue Apr 12 00:25:58 2016
But not only the timezone but the H:M:S are wrong
As date returns me the below information:
$ date
Mon Apr 11 18:06:27 PDT 2016
How to correct it?
This one involves utilizing datetime to great the format you wish with the strftime module.
What's important is that the time information you get 'MUST' be UTC in order to do this. Otherwise, you're doomed D:
I'm using timedelta to 'add' hours to the time. It will also increments the date, too. I still would recommend using the module I shared above to handle time zones.
import time
# import datetime so you could play with time
import datetime
print int(time.time())
date = time.gmtime(1460420758)
# Transform time into datetime
new_date = datetime.datetime(*date[:6])
new_date = new_date + datetime.timedelta(hours=8)
# Utilize datetime's strftime and manipulate it to what you want
print new_date.strftime('%a %b %d %X PDT %Y')
Related
I want a time in the below-mentioned format, using Python.
Tue, 08 Nov 2022 15:35:20 GMT
I should be able to get the current time in above format;
Then I should be able to add days in it and get the date and time in the same above-mentioned format (for example, I want date falling on after n number of days).
Any help would be highly appreciated.
I have tried the below code but not getting the desired results:
start_date = str(datetime.now()).split(".")[0]
due_date = str((datetime.now() + timedelta(days=2))).split(".")[0]
Output:
2022-11-08 23:45:15
2022-11-10 23:45:15
You can try to use the below functions:
from datetime import datetime, timedelta
def get_now():
return datetime.now().strftime('%a, %d %b %Y %H:%M:%S GMT')
def n_days_from_now(n):
now = get_now()
return (datetime.now() + timedelta(days = n)).strftime('%a, %d %b %Y %H:%M:%S GMT')
This is the data that is being returned from my API:
"Jun 02, 2021, 2 PMEST"
If I'm within 7 days of the current date which I'm getting by doing this:
from datetime import date
today = date.today()
print("Today's date:", today)
Just need to convert Jun to a number and 02 and compare to see if it's within 7 days in the future of the current date, then return True
APPROACH 0:
Given the format of your example data, you should be able to convert it to a datetime using this code:
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
The details about this format string are here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
However, when I tested this locally, it worked for this input:
"Jun 02, 2021, 2 PMUTC"
but not for your input (which has different timezone):
"Jun 02, 2021, 2 PMEST"
I have investigated this some more and "read the docs" (https://docs.python.org/3/library/time.html).
To get EST parsing to work, you would have to change your OS timezone and reset the time module's timezones like this:
from datetime import datetime
import os
import time
os.environ["TZ"] = "US/Eastern". # change timezone
time.tzset(). # reset time.tzname tuple
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
When you're done, be safe and delete the "hacked" environment variable:
del os.environ["TZ"]
Note - Since your system timezone is presumably still UTC, it can still parse UTC timezone too.
See this thread for detailed discussion: https://bugs.python.org/issue22377
Also note that the timestamp is not actually captured. The result you get with EST and UTC is a naive datetime object.
APPROACH 1
So, it seems like there is a better way to approach this.
First, you need to pip install dateutils if you don't already have it.
THen do something like this:
from dateutil import parser
from dateutil.tz import gettz
tzinfos = {"EST": gettz("US/Eastern")}
my_datetime = parser.parse("Jun 02, 2021, 2 PM EST", tzinfos=tzinfos)
What's happening here is we use gettz to get timezone information from the timezones listed in usr/share/zoneinfo. Then the parse function can (fuzzy) parse your string (no format needs to be specified!) and returns my_datetime which has timezone information on it. Here are the parser docs: https://dateutil.readthedocs.io/en/stable/parser.html
I don't know how many different timezones you need to deal with so the rest is up to you. Good luck.
Convert the date to a datetime structure and take the direct difference. Note that today must be a datetime, too.
import datetime
date_string = "Jun 02, 2021, 2 PMEST"
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_string,
"%b %d, %Y, %I %p%Z") # Corrected
(date - today).days
#340
This question already has answers here:
Parse CEST/CET time in python
(2 answers)
Closed 5 years ago.
I am creating simple RSS reader. Storing date of last read newest entry in newest_entry_datetime and then when reading again channel I am comparing entry time to newest_entry_datetime with < symbol as I read that Python is smart enough to recognize and compare datetime.
It works on the same day when time part is changing but on the next day newest date is implemented as old.
import datetime
import locale
#locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
#dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S %Z" )
if (entry_published <= newest_entry_datetime):
print('Entry date is older')
else:
print('Entry date is NEW')
With such code I am getting result: "Entry date is older" which is wrong.
Second idea was to convert datestamps to datetime but I am getting:
ValueError: time data 'Thu, 21 Dec 2017 16:02:03 CET' does not match format '%a, %d %b %Y %H:%M:%S %Z'
even if I will change locale to US.
No clue how to do that correctly. Could you please help?
Thanks to Anton vBR answer that CET is not recognized I just removed this part of string as feed will always have the same timezone.
Final code that works and gives proper result is here.
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
newest_entry_datetime = newest_entry_datetime.rsplit(" ", maxsplit=1)[0]
entry_published = entry_published.rsplit(" ", maxsplit=1)[0]
dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S" )
st_entry = datetime.datetime.strptime (entry_published, "%a, %d %b %Y %H:%M:%S" )
if (st_entry <= dt_newest):
print('Entry date is older')
else:
print('Entry date is NEW')
Result is: 'Entry date is NEW' as it was expected.
If you compare you "dates" before converting to datetime - you compare strings. First you need convert to datetime (use for it right format if current is not support you string datetime style), and after that you can compare two datetime objects.
You can't convert to datetime to this format because of 'CET', for timezones you can you custom desicion (like this).
What is the correct format to convert this string Tue Jan 10 2017 13:00:13 GMT 0800 (Taipei Standard Time) to a python date type object using strptime?
I tried the answer from this question and it is not working for me:
date1 = datetime.strptime(strDate1, '%b %d %Y %I:%M%p')
ValueError: time data 'Tue Jan 10 2017 13:00:13 GMT 0800 (Taipei
Standard Time)' does not match format '%b %d %Y %I:%M%p'
You can format the date without timezone and add it later,
import pytz
date1=datetime.strptime('Tue Jan 10 2017 13:00:13', '%a %b %d %Y %H:%M:%S')
tz=pytz.timezone('Asia/Taipei')
tz.localize(date1)
Nominally you would want to be able to use the %z (lowercase z) to convert the TZ offset, however support for this is sketchy. So you can DIY it:
import datetime as dt
import re
PARSE_TIMESTAMP = re.compile('(.*) ([+-]?\d+) \(.*\)$')
def my_datetime_parse(timestamp):
''' return a naive datetime relative to UTC '''
# find the standard time stamp, and the TZ offset and remove extra end
matches = PARSE_TIMESTAMP.match(timestamp).groups()
# convert the timestamp element
timestamp = dt.datetime.strptime(matches[0], '%a %b %d %Y %H:%M:%S %Z')
# calculate the timezone offset
tz_offset = matches[1]
sign = '+'
if tz_offset[0] in '-+':
sign = tz_offset[0]
tz_offset = tz_offset[1:]
tz_offset += '0' * (4 - len(tz_offset))
minutes = int(tz_offset[0:2]) * 60 + int(tz_offset[2:])
if sign == '-':
minutes = -minutes
# add the timezone offset to our time
timestamp += dt.timedelta(minutes=minutes)
return timestamp
date_string = 'Tue Jan 10 2017 13:00:13 GMT +0800 (Taipei Standard Time)'
print(my_datetime_parse(date_string))
This code produces:
2017-01-10 21:00:13
The code removes the (Taipei Standard Time) since it is redundant with the +0800.
I'm creating a python script that will display busy, no-answer and failed calls for a specific date but I'm stuck on the formatting of the date that's displayed. The start_time and end_time "variables" from Twilio print something like this: "Mon, 25 Jul 2016 16:03:53 +0000". I want to get rid of the day name and the comma since I'm saving the results into a csv file (script_name.py > some_file.csv) and the comma after the day name kind of screws up the csv structure.
In the settings.py file the time_zone variable is set to the right one (America/Chicago) and the USE_TZ variable is set to true. But anyway the output is still in UTC.
I don't know anything about Python and the things I've tried to parse call.start_time to a datetime have failed . . . I would know how to do it if it was a given value like start_time = '2016-07-26', but I don't know how to do it when the value comes from for call in client.calls.list . . .
Any guidance will be greatly appreciated!
Thanks!
from twilio.rest import TwilioRestClient
from datetime import datetime
from pytz import timezone
from dateutil import tz
# To find these visit https://www.twilio.com/user/account
account_sid = "**********************************"
auth_token = "**********************************"
client = TwilioRestClient(account_sid, auth_token)
for call in client.calls.list(
start_time="2016-07-25",
end_time="2016-07-25",
status='failed',
):
print(datetime.datetime.strptime(call.start_time, "%Y-%m-%d %H:%M:%S"))
The code I've provided does simple date and time format.
from datetime import datetime
from time import sleep
print('The Time is shown below!')
while True:
time = str(datetime.now())
time = list(time)
for i in range(10):
time.pop(len(time)-1)
time = ('').join(time)
time = time.split()
date = time[0]
time = time[1]
print('Time: '+time+', Date: '+date, end='\r')
sleep(1)
However if you looking just to format "Mon, 25 Jul 2016 16:03:53 +0000" as you said and just remove the day consider something like this:
day = "Mon, 25 Jul 2016 16:03:53 +0000"
# Convert to an array
day = list(day)
# Remove first 5 characters
for i in range(5):
day.pop(0)
day = ('').join(day)
print(day)
# You can use if statements to determine which day it is to decide how many characters to remove.
>>> "25 Jul 2016 16:03:53 +0000"
The format you need to parse is dictated by the timestamp provided by Twillo. You will likely need the following format string to properly parse the timestamp:
print(datetime.datetime.strptime(call.start_time, "%a, %d %b %Y %H:%M:%S %z"))
A great guide for the formatting string is http://strftime.org/.
Another good library for lazily converting dates from strings is the python-dateutil library found at https://dateutil.readthedocs.io/.