fetch timezone and covert to utc - python-3.x

I have a requirement which has input as 2020-03-21T11:23:50-05:00, and output should be two different variables
covertedutc : 2020-03-21 16:23:50
timezone : -05:00
i have tried without timezone in input variable and below is snippet
import datetime
import pytz
timestring = "2020-03-21T11:23:50"
# Create datetime object
d = datetime.datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%S")
print(d.strftime("%d.%m.%y %H:%M:%S"))

This should do the trick:
from datetime import datetime, timedelta
variable='2020-03-21T11:23:50-05:00'
variable = " ".join(variable.split("T")) #eliminating the "T"
converted = datetime.strptime(variable[:19], '%Y-%m-%d %H:%M:%S') + timedelta(hours=5)
print(f'covertedutc {converted}')
print(f'timezone {variable[19:]}')
Output:
covertedutc 2020-03-21 16:23:50
timezone -05:00

Related

Need to convert a date into target timezone date with DST (daylight savings time)

I have a datetime in this format "20200123114953". I am able to convert the datetime to target timezone datetime as "2020-01-23T00:19:53-0600", in this it is not respecting daylight saving.
I expect the time with offset value "-5:00", but I get "-6:00" for US/Eastern.
Could someone please help me out with the logic in Python that respects DST?
import datetime as dt
import pendulum
import pytz
def getDateTime(datetime_, is_timezone_required=None, input_format=None, output_format=None, default='False'):
is_timezone_required = False if is_timezone_required.lower() in ["false"] else True
timezone = None
input_format = "%Y%m%d%H%M%S"
output_format = "%Y-%m-%dT%H:%M:%Sz"
timezone = "US/Eastern"
if is_timezone_required:
if "%z" not in output_format:
output_format += "%z"
else:
if "%z" in output_format:
output_format = output_format.replace("%z", "")
datetime_object = dt.datetime.strptime(datetime_, input_format)
timezone_py = pytz.timezone(timezone)
datetime_object = datetime_object.astimezone(timezone_py)
output = dt.datetime.strftime(datetime_object, output_format)
return output
getDate = getDateTime('20200123114953', "True")
print(getDate)
"This gets an output: 2020-01-23T01:19:53z-0500
My expectation is : 2020-01-23T02:19:53z-0400"

How to turn this datetime format without any other characters?

I want my datetime format to be like this "20210613172123" from this "2021-06-13 17:21:23.039823". Is this possible in python?
import datetime
now = datetime.datetime.now()
print(now)
So this is what you need to do :
from datetime import datetime
now = datetime.now()
formatted_time_expression = f'{now.year}{now.month}{now.day}{now.hour}{now.minute}{now.second}{now.microsecond}'
print(formatted_time_expression)
Use strftime to convert datetime object to the required string format.
from datetime import datetime
now = datetime.now()
print(now)
print(now.strftime("%Y%m%d%H%M%S"))
datetime to timestamp
from datetime import datetime
# current date and time
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)
timestamp to datetime
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

How to covert simple date-string to ISO-date format in python?

I'm able to convert ISO-date format to simple date format as below.
from dateutil.parser import parse
date_string = '2018-03-12T10:12:45Z'
dt = parse(date_string)
print(dt.date()) #prints 2018-03-12
print(dt.time()) #prints 10:12:45
print(dt.tzinfo) #prints tzutc()
How to convert it other way ? examples shown below
If input is `2018-03-12` , then output should be `2018-03-12T00:00:00Z`
If input is `2018-03-12-10-12-45` , then output should be `2018-03-12T10:12:45Z`
I am accepting two inputs (format : yyyy-mm-dd) and trying to form date-range between from-date and to-date in iso-format. How can I do that (as below) ?
input1 : `2018-03-12` , output1 : `2018-03-12T00:00:000Z` (12AM, 24-hr format)
input2 : `2018-03-15` , output2 : `2018-03-15T23:59:000Z` (11:59PM, 24-hr format)
Solution:
import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)
Output:
2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z
you can use datetime module (if there is only 2 expected patterns, you can simply do try-except)
str_date = '2018-03-12'
def convert(x):
try:
return datetime.strptime(x, '%Y-%m-%d-%H-%M-%S')
except ValueError:
return datetime.strptime(x, '%Y-%m-%d')
convert(str_date)
Solution:
import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)
Output:
2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z

How to get the date in the form of month(string) day(int) year(int)?

I was wondering how to get the date in the form of month(string) day(int) year(int) using only python?
You can use dparser to get something similar:
import dateutil.parser as dparser
from datetime import datetime, date
today = date.today()
print(datetime.date(dparser.parse(str(today),fuzzy=True)).strftime("%B, %d, %Y"))
OUTPUT:
April, 24, 2020

Converting string with nano seconds to timestamp

Im trying to convert String Datatype to Timestamp data type but Im getting NONE as a result
Sample Data and Code
20181016T192403.635918+02:00
date_format = "yyyyMMdd'T'HHmmss.SSSSSSZ”
data_frame = data_frame.withColumn('dob_ts', unix_timestamp('dob', date_format).cast(‘timestamp’)
Other formats (yyyyMMdd'T'HHmmss.SSS) works fine but not this one.
How to convert this format to timestamp?
You can using udf to define your function. Hence, in the user defined function you can handle this case by an if or what you want:
from pyspark.sql.functions import udf
from datetime import datetime
from pyspark.sql.types import TimestampType
def date_time_to_date(input_date_time):
split_ind = input_date_time.find('T')
new_date = input_date_time
if split_ind > -1:
new_date = input_date_time[:split_ind] + input_date_time[split_ind + 1:]
return datetime.strptime(input_date_time, '%Y%m%d %H%M%S.%f')
udf_date_time_to_date = udf(new_date, TimestampType())
data_frame = data_frame.withColumn('dob_ts', udf_date_time_to_date('dob'))

Resources