How can I convert datetime to unix timestamp in python - python

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)

Related

web scraping convert unix timestamp to date format

I'm trying to webscrape a flight data website using beautifulsoup in python but the timestamp is in unix timestamp how can i convert to regular datetime format. There are several such columns to be converted.
#scheduled_departure
result_items[0]['flight']['time']['scheduled']['departure']
and the output is shown as 1655781000. how can I convert it to Tue, Jun 21, 2022 8:40 AM
import time
print(time.strftime("%a, %b %d, %Y %H:%M %p", time.localtime(1655781000)))
There is only one Unix time and it is created by using the UTC/GMT time zone. This means you might have convert time zones to calculate timestamps.
import datetime
from pytz import timezone
local_datetime = datetime.datetime.fromtimestamp(1655781000)
local_time_str = datetime.datetime.strftime(local_datetime, "%a, %d %b %Y %H:%M:%S %p")
print(f'Local time: {local_time_str}')
other_timezone = 'Asia/Kolkata' # Replace your interest timezone here
remote_datetime = local_datetime.astimezone(timezone(other_timezone))
remote_time_str = datetime.datetime.strftime(remote_datetime, "%a, %d %b %Y %H:%M:%S %p")
print(f'Time at {other_timezone }: {remote_time_str}')

How to create date timestamp logs like git log

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

Converting from unix time string to python date type, Does not convert when CDT is present

I have a date time string in this format in python
"Wed Mar 20 00:52:54 CDT 2019 20 Mar 2019"
I am trying to convert this to python date time format using below code
datetime.datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S %Y")
But it gives error as CDT is present in the text. How to handle this problem. I am not sure if CDT will be present for all dates. In both cases i want to convert.
My requirement is only to get the difference in days between this date and now
Use CDT in the format, then calculate the difference between now and that date. Finally print delta.days.
from datetime import datetime
date0 = datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S CDT %Y")
date_now = datetime.now()
delta = date_now - date0
print(delta.days)
Output in this case:
0
If you're not sure if there will be CDT, check the string before passing it to strptime. Or use try/except:
try:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S CDT %Y")
except ValueError:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S %Y")

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

Convert string to python date type object with timezone offset using strptime

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.

Categories

Resources