How to Format a Datetime in a Different Format

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

How to format date string via multiple formats in python

Try each format and see if it works:

from datetime import datetime

def try_parsing_date(text):
for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
try:
return datetime.strptime(text, fmt)
except ValueError:
pass
raise ValueError('no valid date format found')

How to change the datetime format in Pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
DOB
0 26/1/2016
1 26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
DOB DOB1
0 2016-01-26 01/26/2016
1 2016-01-26 01/26/2016

Datetime column with two different format

Assuming OP only has either strings in format of %Y-%m-%d %H:%M:%S.%f or unix timestamps or NaN in his dataFrame:

from datetime import datetime
import pandas as pd

def unix_or_dt(a):
my_format = '%Y/%m/%d %H/%M/%S'
try:
return datetime.strptime(str(a), '%Y-%m-%d %H:%M:%S.%f').strftime(my_format)
except:
return datetime.utcfromtimestamp(int(a[:10])).strftime(my_format)

data = pd.read_csv('data.csv')\

data.dropna(inplace=True)

data['formatted'] = data['datetime'].apply(lambda row: unix_or_dt(row))

data

This deals with the nulls and the unix number too large to store issue

Change DateTime Format as yyyy-mm-dd

From DateTime.ParseExact

Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.

In your case, they are not.

You can use dd/M/yyyy hh:mm:ss tt format instead. Here an example;

string s = "13/5/2014 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd/M/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine(date);

DateTime has no implicit format, it is just a DateTime value. You can format it as string with DateTime.ToString() method like;

date.ToString("yyyy-M-dd hh:mm:ss");

Take a look at;

  • Custom Date and Time Format Strings

C# DateTime to YYYYMMDDHHMMSS format

DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive


Related Topics



Leave a reply



Submit