How to turn this datetime format without any other characters? - python-3.x

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))

Related

How do I search for a string containing today's date/dates in a file using python?

rom pathlib import Path
path = Path('/home/hell/Downloads/hello by Adele/')
search_string = 'completed on "%d/%m/%Y"' #%d/%m/%Y today's date
t=0
for o in path.rglob('*.sql'):
if o.is_file():
t= t+1
text = o.read_text()
if search_string not in text:
print(o)
break
search_string = 'completed on "%d/%m/%Y"'
the script is to search for a string.."completed on 13/13/2022". I would like to add date to the current date to the search parameter but cant figure out how.
kindly assist and thanks
first get your today's date to string
from datetime import datetime
dateText = datetime.now().strftime("%d/%m/%Y")
then concat your "search_string"
search_string ='completed on '+dateText
>>> from datetime import datetime
>>> dateText = datetime.now().strftime("%d/%m/%Y")
>>> search_string ='completed on '+dateText
>>> print(search_string)
completed on 26/09/2022
If you use the datetime library, you can get 'today' with
from datetime import date
t = date.today()
This will be a datetime.date object. You can then display it in whatever format you want with the .strftime() method, so you'd have display_date = t.strftime('%d/%m/%Y'). Your new object display_date will be a string in that format.
Do all of that first in your script, and then have your search_string = f'completed on {display_date}'
So in total you will have
from pathlib import Path
from datetime import date
t = date.today()
display_date = t.strftime('%d/%m/%Y')
path = Path('/home/hell/Downloads/hello by Adele/')
search_string = f'completed on {display_date}'
t=0
for o in path.rglob('*.sql'):
if o.is_file():
t= t+1
text = o.read_text()
if search_string not in text:
print(o)
break

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 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

fetch timezone and covert to utc

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

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