Chris Hall
Chris Hall

Reputation: 931

Python Ctime conversion

I'm having issues coverting a ctime string over to %Y-%m-%d format.

fileobject = "C:\\foo\\bar.txt"
filetime = time.ctime(os.path.getctime(fileobject))

print filetime
Wed Feb 03 11:02:38 2016

Now I just want to convert to YYYY-MM-DD. Any suggestions? I'm not having luck with traditional reformatting

Upvotes: 1

Views: 4209

Answers (5)

jfs
jfs

Reputation: 414139

You should avoid "Yo-Yo code" and format the file time in the desired format directly without converting it to a string using ctime() first:

#!/usr/bin/env python
import os
from datetime import datetime

filename = r"C:\foo\bar.txt"
dt = datetime.fromtimestamp(os.path.getmtime(filename))
print(dt.date())
# -> 2016-02-03

If you've received ctime()-formated time string from an external source then you could parse this (asctime()) date/time format using email stdlib package:

>>> from email.utils import parsedate
>>> parsedate('Wed Feb 03 11:02:38 2016')[:3]
(2016, 2, 3)
>>> "%04d-%02d-%02d" % _
'2016-02-03'

In general, use datetime.strptime() to convert a string into datetime object. See Converting string into datetime.

Upvotes: 2

KarolisR
KarolisR

Reputation: 626

You can use strptime and then strftime:

>>> print datetime.datetime.strptime(filetime, "%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d")
2016-02-03

Upvotes: 0

Dan D.
Dan D.

Reputation: 74645

Use time.strftime with time.localtime rather than using time.ctime:

>>> print time.strftime("%Y-%m-%d", time.localtime(os.path.getctime(fileobject)))
2015-10-20

I won't tell you the file I used so the output will differ.

Upvotes: 2

dima
dima

Reputation: 158

use

time.strptime(string[, format])

to format the output

https://docs.python.org/2/library/time.html

Upvotes: 0

Andy
Andy

Reputation: 50540

The filetime is a string. That means you can use time.strptime to parse it.

cdt = time.strptime(filetime, "%a %b %d %H:%M:%S %Y")

At this point, cdt is a struct_time object and you can manipulate it as such.

>>> cdt
time.struct_time(tm_year=2015, tm_mon=11, tm_mday=22, tm_hour=0, tm_min=37, tm_sec=9, tm_wday=6, tm_yday=326, tm_isdst=-1)

Upvotes: 0

Related Questions