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')
Related
I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.
I am using the following code ===>
news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())
But gives the following error ===>
ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
How can i solve it and get the unix timestamp from this?
%Z can't parse the timezone name PT - I suggest you skip parsing it and add it "manually" instead:
from datetime import datetime
import dateutil
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))
# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0
if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.
tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)
Using datetime.datetime.now(), I receive some badly formatted timestamps.
Is there an intuitive way of creating a date timestamp in this format?
Wed Aug 7 13:38:59 2019 -0500
This is seen in git log.
You can use datetime.datetime.strftime() to format dates as shown below:
from datetime import datetime
d = '2019-08-07 13:38:59-0500'
d2 = datetime.strptime(d, '%Y-%m-%d %H:%M:%S%z')
d3 = d2.strftime('%a %b %d %H:%M:%S %Y %z')
print(d3)
This returns:
Wed Aug 07 13:38:59 2019 -050000
This website is a great resource for strftime formatting.
You can still use the datetime library. Using strftime, you can rewrite the datetime object into a nicely formatted string.
In your case, you are going for Wed Aug 7 13:38:59 2019 -0500, which translated to strftime formatting is "%a %b %d %H:%M:%S %Y %z".
Overall, it'd be
datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y %z")
Which will give a string that looks like 'Wed Aug 7 13:38:59 2019 -0500'.
I would do the following:
from time import gmtime, strftime
if __name__ == "__main__":
time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
print(time)
This was found on the documentation page of the time module. There are also a lot of additional features you might be interested in using outlined here: https://docs.python.org/3/library/time.html#time.strftime
I have two timestamp strings. I want to find the difference between them in seconds.
I've tried:
from time import gmtime, strptime
a = "Mon 11 Dec 2017 13:54:36 -0700"
b = "Mon 11 Dec 2017 13:54:36 -0000"
time1 = strptime(a, "%a %d %b %Y %H:%M:%S %z")
time2 = strptime(b, "%a %d %b %Y %H:%M:%S %z")
time1-time2
Getting an error: TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'
So, how do I calculate the difference using package time?
I was successful using package datetime - in the code below, but I think I read that datetime ignores seconds in leap years, or something to that effect. Thus, I am trying to use 'time':
from datetime import datetime
time1 = datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
time2 = datetime.strptime(b, "%a %d %b %Y %H:%M:%S %z")
dif = time1 - time2
print(int(dif.total_seconds()))
Thank you very much!
First of all, you're using time.strptime, which returns <class 'time.struct_time'>, and it doesn't support the substract operator, one possible way to achieve what you want would be converting to datetime:
from datetime import datetime
from time import mktime
from time import gmtime, strptime
a = "Mon 11 Dec 2017 13:54:36 -0700"
b = "Mon 11 Dec 2017 13:54:36 -0000"
time1 = strptime(a, "%a %d %b %Y %H:%M:%S %z")
time2 = strptime(b, "%a %d %b %Y %H:%M:%S %z")
print(datetime.fromtimestamp(mktime(time1))-datetime.fromtimestamp(mktime(time2)))
Or even better, use datetime.datetime.strptime so you don't need intermediate conversions.
For a more detailed description of the supported operations of datetime please refer to the section supported operations in the docs here. Especially the section where it says:
If both are aware and have different tzinfo attributes, a-b acts as if
a and b were first converted to naive UTC datetimes first. The result
is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
- b.utcoffset()) except that the implementation never overflows.
In any case, maybe your best chance is considering an alternative method like the one proposed in this answer
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.
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')