Convert year from unicode format to python's datetime format - python

I have only year parameter as input in the following manner:
2014,2015,2016
I want to convert each element from my list into python's datetime format. Is it possible to do this kind of things if the only given parameter is the year ?

Just set month and day manually to 1
from datetime import date
YearLst = [2014,2015,2016]
map(lambda t: date(t, 1, 1),YearLst)

Related

Convert custom string date to date

Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime (or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replaces but im hoping to find a clean single operation to do this.
You might provide datetime.datetime.strptime with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here's an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)

Python how to convert datetime.date to the YYYY-MM-DD? [duplicate]

This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 8 months ago.
I have a two million timestamp data. I am trying to find first and last date that to in the YYYY-MM-DD format so I can use them in saving file name. But, I found out that np.unique(df.index) is fast (10s) and produces dates in the
datetime.date(2022, 6, 7) format but df.index.strftime('%Y-%m-%d').unique() gives the output I want but it takes more than 5 min, which is bad. So, I decided to use the former approach.
So, How do I convert something like datetime.date(2022, 6, 7) to'2022-06-07'?
Just put that into the str(...) function:
import datetime
my_date = datetime.date(2022, 6, 7)
print(str(my_date)) # prints 2022-06-07
Technically, you can just print it and not make it a string first. But putting it in str means that instead of printing it, you could save that string to a variable.
If you need more advanced formatting options, then you can do what #FObersteiner suggested. But the format you want happens to be the default, so this will do if you just want that one format
Try this:
# import datetime module
from datetime import datetime
# consider date in string format
my_date = "30-May-2020-15:59:02"
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.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.

Converting 23/Oct/2014 to 2014/10/23 in Python

I have date strings in the form of '23/Oct/2014' and want to convert it to '2014/10/23' in Python 3. The final output I need is just as a string. I implementing my own function to do the conversion using dictionary (for month conversion) but I am wondering if there is more pythonic way of doing the same thing.
You can use the datetime library to parse the string, then format back to a string again:
from datetime import datetime
converted = datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')
This parses the input string using datetime.datetime.strptime(), then formats the resulting object to a string again with datetime.datetime.strftime().
Demo:
>>> from datetime import datetime
>>> original = '23/Oct/2014'
>>> datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')
'2014/10/23'
If you just want a string, your dict mapping and format would work fine, if you don't want datetime objects I don't see the point in using datetime:
dt = '23/Oct/2014'
dates = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05", Jun="06", Jul="07", Aug="08", Sep="09", Oct="10",
Nov="11", Dec="12")
day,mon, year = dt.split("/")
print("{}/{}/{}".format(year,dates[mon],day))
2014/10/23

Categories