python parse string in date format to get the date - python

There is a string and a date format. I want to get the date based on format.
If date format is YYYY.MM.dd and string is 2017.01.01. It should transform to a valid date object.
How can I find the date.

You can use datetime module something like this :
from datetime import datetime
date_object = datetime.strptime('2017.01.01', '%Y.%m.%d') # Converting the given date string into a datetime object.
formatted_date = date_object.strftime('%c') #User Defined Output Format
print(formatted_date)
This will result in :
Sun Jan 1 00:00:00 2017
You can refer to the documentation here.

Related

Convert string of dd-MON-yy to date in Python

I have a string in dd-MON-yy format. While converting to date in python, its is causing issue since the year is in tow digits.
datetime.datetime.strptime('17-JUN-03', '%d-%m-%y')
The error is,
ValueError: time data '17-JUN-03' does not match format '%d-%m-%y'
Try this:
import datetime
print(datetime.datetime.strptime('17-JUN-03', '%d-%b-%y'))
Result:
2003-06-17 00:00:00
Datetime format codes

How to increase timestamp string to timestamp with new year, month, day Python datetime?

I want to write a function that takes in a string representing timestamp, then change the year, month and day of that timestamp but not the actual time. Then I want to return the resulting timestamp as a string. I'm having some trouble with the conversion, since I think I need to convert in the following sequence: string -> timestamp -> date -> timestamp -> string. I've read through the datetime library, but I'm having some trouble with this conversion. Any assistance, would be much appreciated!
Function inputs would look like this:
def change_date(string: timestamp, string: new_date)
#timestamp: string formatted like 1601403951777
#new_date: string formatted like YYYY-MM-DD
For instance timestamp 1601403951777 is Tuesday, September 29, 2020.
Try this,
from datetime import datetime
def change_date(dt):
#timestamp: string
#new_date: string formatted like YYYY-MM-DD
d= datetime.fromisoformat(dt)
new_date = d.strftime(('%Y-%m-%d'))
print(new_date)
dt = str(datetime.now())
print(dt)
change_date(dt)
output
2021-06-09 16:15:58.421486
2021-06-09
I would recommend using the .replace method of datetime objects:
def change_date(string: timestamp, string: new_date):
source_dt = datetime.fromtimestamp(int(timestamp))
year, month, date = [int(i) for i in new_date.split('-')]
return f"{source_dt.replace(year=year, month=month, date=date):...}"
where {:...} is the format you need.

How to convert millisecond Unix timestamp to readable date?

I have a string 1615070997520. This is a Unix timestamp, but this is for millisecond. When I convert this to date with converter, It gives me correct date (Saturday, March 6, 2021 10:49:57.520 PM GMT).
But with this code:
from datetime import datetime
ts = int("1615070997520")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
It gives me an error which is ValueError: year 53149 is out of range.
Is there any way to convert it into correct date like yyyy-mm-dd hh:mm:ss.ms using Python?
Try this one
ts = int("1615070997520")/1000
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Datetime still showing time component

I have this line of code-
future_end_date = datetime.strptime('2020/02/29','%Y/%m/%d')
and when I print this-
2020-02-29 00:00:00
it still shows the time component even though I did strptime
This is because strptime returns datetime rather than date. Try converting it to date:
datetime.strptime('2020/02/29','%Y/%m/%d').date()
datetime.strptime(date_string, format) function returns a datetime
object corresponding to date_string, parsed according to format.
When you print datetime object, it is formatted as a string in ISO
8601 format, YYYY-MM-DDTHH:MM:SS
So you need to convert the datetime into date if you only want Year, month and Day -
datetime.strptime('2020/02/29','%Y/%m/%d').date()
Another possible way is using strftime() method which returns a string representing date and time using date, time or datetime object.
datetime.strptime('2020/02/29','%Y/%m/%d').strftime('%Y/%m/%d')
Output of both code snippets -
2020/02/29

Extract Date from excel and append it in a list using python

I have an column in excel which has dates in the format ''17-12-2015 19:35". How can I extract the first 2 digits as integers and append it to a list? In this case I need to extract 17 and append it to a list. Can it be done using pandas also?
Code thus far:
import pandas as pd
Location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(Location)
time = df['Creation Date'].tolist()
print (time)
You could extract the day of each timestamp like
from datetime import datetime
import pandas as pd
location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(location)
timestamps = df['Creation Date'].tolist()
dates = [datetime.strptime(timestamp, '%d-%m-%Y %H:%M') for timestamp in timestamps]
days = [date.strftime('%d') for date in dates]
print(days)
The '%d-%m-%Y %H:%M'and '%d' bits are format specififers, that describe how your timestamp is formatted. See e.g. here for a complete list of directives.
datetime.strptime parses a string into a datetimeobject using such a specifier. dateswill thus hold a list of datetime instances instead of strings.
datetime.strftime does the opposite: It turns a datetime object into string, again using a format specifier. %d simply instructs strftime to only output the day of a date.

Categories